Pandas DataFrame,如何删除总和为 0 的所有列和行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23573052/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 22:02:00  来源:igfitidea点击:

Pandas DataFrame, How do I remove all columns and rows that sum to 0

pythonpandas

提问by Brig

I have a dataFrame with rows and columns that sum to 0.

我有一个行和列总和为 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 

The end result should be

最终结果应该是

    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.

请注意,只有零的行和列已被删除。

回答by unutbu

df.loc[row_indexer, column_indexer]allows you to select rows and columns using boolean masks:

df.loc[row_indexer, column_indexer]允许您使用布尔掩码选择行和列:

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) != 0is True if and only if the row does not sum to 0.

df.sum(axis=1) != 0当且仅当行的总和不为 0 时为真。

df.sum(axis=0) != 0is True if and only if the column does not sum to 0.

df.sum(axis=0) != 0当且仅当列的总和不为 0 时为真。

回答by Ziggy Eunicien

building on Drop rows with all zeros in pandas data frameto avoid using the sum()

基础上删除行与Pandas数据帧全部为零,以避免使用总和()

df = pd.DataFrame({'A': [1,0,1,0,1],
                   'B': [1,0,0,1,1],
                   'C': [0,0,0,0,0],
                   'D': [1,0,1,0,1]})

df.loc[(df!=0).any(1), (df!=0).any(0)]

   A  B  D
0  1  1  1
2  1  0  1
3  0  1  0
4  1  1  1

回答by user3218971

This is my way to do it:

这是我的方法:

import pandas as pd 
hl = []
df =  pd.read_csv("my.csv")
l = list(df.columns.values)
for l in l:
    if sum(df[l]) != 0:
        hl.append(l)
df2 = df[hl]

to write reduced_Data:

写入reduced_Data:

df2.to_csv("my_reduced_data.csv")

It will only check columns but ignore Rows

它只会检查列但忽略行