在下面的示例中,我只想保留第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
输出应如下所示:
kt b tt mky depth
1 1 1 1 1 4
2 2 2 2 2 2
我试过了:
df.loc[(df!=0).any(axis=1)]
但是只有当所有相应的列都为0
时才会删除该行答案 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)]