从Pandas数据帧中仅过滤零个列

tur*_*tle 8 python pandas

我有一个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
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?我一直在尝试这样的事情:

df.filter(lambda x: x == 0)
Run Code Online (Sandbox Code Playgroud)

ely*_*ely 10

以下适用于我.它给出了一个系列,其中列名现在是索引,索引的值是True/False,具体取决于列中的所有项是否为0.

import pandas, numpy as np
# Create DataFrame "df" like yours...

df.apply(lambda x: np.all(x==0))
Run Code Online (Sandbox Code Playgroud)

  • 我写'df [df.columns [(df!= 0).any()]]`而不是[必须修复一个错字].无论如何,它似乎在0.8.1中工作. (5认同)