从 Pandas 数据框中过滤只有零的列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12411649/
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
Filter columns of only zeros from a Pandas data frame
提问by turtle
I have a Pandas Data Frame where I would like to filter out all columns which only contain zeros. For example, in the Data Frame below, I'd like to remove column 2:
我有一个 Pandas 数据框,我想过滤掉所有只包含零的列。例如,在下面的数据框中,我想删除第 2 列:
0 1 2 3 4
0 0.381 0.794 0.000 0.964 0.304
1 0.538 0.029 0.000 0.327 0.928
2 0.041 0.312 0.000 0.208 0.284
3 0.406 0.786 0.000 0.334 0.118
4 0.511 0.166 0.000 0.181 0.980
How can I do this? I've been trying something like this:
我怎样才能做到这一点?我一直在尝试这样的事情:
df.filter(lambda x: x == 0)
回答by ely
The following works for me. It gives a series where column names are now the index, and the value for an index is True/False depending on whether all items in the column are 0.
以下对我有用。它给出了一个系列,其中列名现在是索引,索引的值是 True/False 取决于列中的所有项目是否为 0。
import pandas, numpy as np
# Create DataFrame "df" like yours...
df.apply(lambda x: np.all(x==0))

