首页 > 解决方案 > 通过 MultiIndex 值删除数据框行

问题描述

DataFrame带有MultiIndex 布尔组合的 a 中,我想删除没有任何索引值为 True 的行:

T000001 T000025 
True    False   1430.0
False   True    301.0
False   False   7950.0   

将索引条目视为布尔数组不起作用:

df[~df.index.any()]



TypeError                                 Traceback (most recent call last)
<ipython-input-35-caeaa0a17799> in <module>
----> 1 combi.index.any()

~/anaconda3/lib/python3.6/site-packages/pandas/core/ops.py in invalid_op(self, other)
    212     def invalid_op(self, other=None):
    213         raise TypeError("cannot perform {name} with this index type: "
--> 214                         "{typ}".format(name=name, typ=type(self).__name__))
    215 
    216     invalid_op.__name__ = name

TypeError: cannot perform any with this index type: MultiIndex

标签: pandasindexingmulti-index

解决方案


转换MultiIndexDataFrameby MultiIndex.to_frame,删除反转~并检查any每行 by axis=1

df = df[df.index.to_frame().any(axis=1)]
print (df)
T000001  T000025
True     False      1430.0
False    True        301.0
Name: a, dtype: float64

推荐阅读