3 回答
TA贡献1155条经验 获得超0个赞
过滤器函数的正则表达式部分的实现很短,很容易适应多索引场景,在这种情况下您仍然希望只使用多索引的正则表达式 1 部分。我知道这不是对您所问内容的直接回答,因为您是对的,因为实现的过滤器功能不处理多索引。
我在这里遇到了同样的问题,并认为发布我使用过的代码(改编自 pandas 原始代码)可能对其他人来说是一个有用的答案:
import regex as re
def filter_multi(df, index_level_name, regex, axis=0):
def f(x):
return matcher.search(str(x)) is not None
matcher = re.compile(regex)
values = df.axes[axis].get_level_values(index_level_name).map(f)
return df.loc(axis=axis)[values]
使用附录中的代码:
print(df)
print(filter_multi(df, index_level_name='tag', regex='^Assets$', axis=0))
print(filter_multi(df, index_level_name='fy', regex='^2019$', axis=1))
TA贡献1808条经验 获得超4个赞
另一种选择是首先uom从您的索引中删除,应用filter(然后将其应用于唯一的索引tag)并添加uom回您的索引,如
df.reset_index('uom').filter(regex="^Assets$", axis=0).set_index('uom', append=True)TA贡献1802条经验 获得超10个赞
如果你想从多索引的第一部分过滤一个唯一值,你可以使用loc:
df.loc[['Assets']]
这使:
fy 2018 2019 tag uom Assets USD 3.753190e+11 3.385160e+11
如果对于你的实际问题,必须使用过滤器,你应该重置索引未使用的部分并在过滤后将其设置回去:
df.reset_index(level='uom').filter(regex='^Assets$', axis=0).set_index('uom', append=True)添加回答
举报
