如果pandas中的任何值为0,如何删除整行

时间:2018-03-17 13:07:30

标签: python-3.x pandas dataframe

在下面的示例中,我只想保留第1行和第2行 我想删除列中任何位置为0的所有行:

kt  b   tt  mky depth
1   1   1   1   1   4
2   2   2   2   2   2
3   3   3   0   3   3
4   0   4   0   0   0
5   5   5   5   5   0

enter image description here

输出应如下所示:

kt  b   tt  mky depth
1   1   1   1   1   4
2   2   2   2   2   2

enter image description here

我试过了:

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

但是只有当所有相应的列都为0

时才会删除该行

1 个答案:

答案 0 :(得分:2)

您非常接近,需要DataFrame.all才能检查每行True

df = df.loc[(df!=0).all(axis=1)] 
print (df)
   kt  b  tt  mky  depth
1   1  1   1    1      4
2   2  2   2    2      2

<强>详情:

print (df!=0)
      kt     b     tt    mky  depth
1   True  True   True   True   True
2   True  True   True   True   True
3   True  True  False   True   True
4  False  True  False  False  False
5   True  True   True   True  False

print ((df!=0).all(axis=1))
1     True
2     True
3    False
4    False
5    False
dtype: bool

使用any的备用解决方案,对于更改了掩码True并按df == 0反转的行,至少检查一个~

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