Python Pandas 过滤零单元格

标签 python python-2.7 pandas

我正在尝试通过所有非零来过滤数据帧。我的 df 是:

    Name    Fruit   Total
0   Steve   Orange  0
1   Bob     Apple   15
2   Cindy   Grapes  27
3   Grant   Orange  37

我想从数据 DF 中删除 Steve。这里是 Pandas 新手,但我已经尝试过了,但似乎不起作用。我尝试查看 loc 的文档,但我认为我缺少一些有关如何使用 loc 的内容。

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

这只是一个示例。我想删除所有为零的总计。

最佳答案

使用boolean indexing :

print (df[~(df==0).any(axis=1)])
    Name   Fruit  Total
1    Bob   Apple     15
2  Cindy  Grapes     27
3  Grant  Orange     37

但是如果列Total中只有数字,则使用:

df[df.Total != 0]

说明:

如果 DataFrame 中有更多数字列 - 那么您不仅可以在最后一列中获得 0 ,而且还可以在其他列中获得 0 ,请使用:

首先将所有值与0进行比较 - 获取boolean DataFrame:

print (df==0)
    Name  Fruit  Total
0  False  False   True
1  False  False  False
2  False  False  False
3  False  False  False

如果需要每列至少找到一个 True (0) anyaxis=0:

print ((df==0).any(axis=0))
Name     False
Fruit    False
Total     True
dtype: bool

但如果每行至少需要一个 True (0),请添加 axis=1:

print ((df==0).any(axis=1))
0     True
1    False
2    False
3    False
dtype: bool

通过~反转 bool 系列:

print (~(df==0).any(axis=1))
0    False
1     True
2     True
3     True
dtype: bool

并使用 bool 索引:

print (df[~(df==0).any(axis=1)])
    Name   Fruit  Total
1    Bob   Apple     15
2  Cindy  Grapes     27
3  Grant  Orange     37

关于Python Pandas 过滤零单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40658291/

相关文章:

python - Pandas:如何用字典替换列表项?

python - 从 pyqtgraph.Qt 导入 QtGui 作为 *

python - 使用 zip 形成新的数据框,但出现错误

excel - python pandas to_excel设置单元格背景颜色

python - 从特定日期的 pandas DataFrame 中选择行

python - 将相同的函数与不同的参数组合起来 - Python

python - 部署 Django 静态文件 - Heroku

Python dateutil.rrule 非常慢

python-2.7 - 使用设置的开始时间码将时间码转换为帧

Python DataFrame 替换 '+'