Pandas DataFrame,如何删除总和为0的所有列和行 [英] Pandas DataFrame, How do I remove all columns and rows that sum to 0
本文介绍了Pandas DataFrame,如何删除总和为0的所有列和行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个dataFrame,其中行和列的总和为0.
I have a dataFrame with rows and columns that sum to 0.
A B C D
0 1 1 0 1
1 0 0 0 0
2 1 0 0 1
3 0 1 0 0
4 1 1 0 1
最终结果应该是
A B D
0 1 1 1
2 1 0 1
3 0 1 0
4 1 1 1
请注意,只有零的行和列已被删除.
Notice the rows and columns that only had zeros have been removed.
推荐答案
df.loc[row_indexer, column_indexer]
允许您使用布尔掩码选择行和列:
df.loc[row_indexer, column_indexer]
allows you to select rows and columns using boolean masks:
In [88]: df.loc[(df.sum(axis=1) != 0), (df.sum(axis=0) != 0)]
Out[88]:
A B D
0 1 1 1
2 1 0 1
3 0 1 0
4 1 1 1
[4 rows x 3 columns]
df.sum(axis=1) != 0
为真,当且仅当行的总和不为0时.
df.sum(axis=1) != 0
is True if and only if the row does not sum to 0.
df.sum(axis=0) != 0
当且仅当列的总和不为0时,才为True.
df.sum(axis=0) != 0
is True if and only if the column does not sum to 0.
这篇关于Pandas DataFrame,如何删除总和为0的所有列和行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文