pandas - 通过 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
解决方案
转换MultiIndex
为DataFrame
by 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
推荐阅读
- c++ - 是否可以在 C++ 中创建可以表示多个结构的数据类型?
- php - 连接来自多个表的用户数据并将该信息返回给特定用户?
- javascript - 如何克隆一个元素?
- ios - iOS 故事板中的视图控制器被分组到另一个故事板中
- javascript - 如果不在 URL 中使用 www,则图像损坏
- mysql - 在 eloquent 中添加 if 语句然后加入另一个表
- jquery - 使用服务器端数据表的下拉选择 | PHP, SQL 服务器
- android - 是否可以安装两个 Android APK 但在启动器上只显示一个?
- algorithm - 删除和移动数组中元素的算法
- php - Laravel 多对多关系的 Laravel Collective 复选框元素