Python 仅当所有列都包含0时才删除该行

Python 仅当所有列都包含0时才删除该行,python,pandas,Python,Pandas,我试图删除所有3列中都包含0的行,我尝试使用这些代码,但它删除了3列中任何一列中包含0的所有行 indexNames = news[ news['contain1']&news['contain2'] &news['contain3']== 0 ].index news.drop(indexNames , inplace=True) 我的CSV文件 contain1 contain2 contain3 1 0 0 0

我试图删除所有3列中都包含0的行,我尝试使用这些代码,但它删除了3列中任何一列中包含0的所有行

indexNames = news[ news['contain1']&news['contain2'] &news['contain3']== 0 ].index
news.drop(indexNames , inplace=True)
我的CSV文件

contain1  contain2  contain3
   1        0         0
   0        0         0
   0        1         1
   1        0         1
   0        0         0
   1        1         1
使用我使用的代码,我的所有行都将被删除。下面是我想要的结果

contain1  contain2  contain3
   1        0         0
   0        1         1
   1        0         1
   1        1         1

如果这是一个数据帧,您可以使用
.sum()
对索引求和


(注意:未测试,仅从内存中测试)

一个简单的解决方案是根据列的总和进行过滤。您可以通过运行此代码
news[news.sum(axis=1)!=0]
来完成此操作。
希望这对您有所帮助:)

您可能想试试这个

news[(news.T != 0).any()]
首先筛选不相等的
0
,然后获取至少有一个匹配项的行-因此仅通过以下方式删除
0
行:

详情:

print (news.ne(0))
   contain1  contain2  contain3
0      True     False     False
1     False     False     False
2     False      True      True
3      True     False      True
4     False     False     False
5      True      True      True

print (news.ne(0).any(axis=1))
0     True
1    False
2     True
3     True
4    False
5     True
dtype: bool

尝试
news['contain1']==0和news['contain2']==0和news['contain3']==0
@KeithJohnHutchison我得到了这个错误值error:一个系列的真值不明确。使用a.empty、a.bool()、a.item()、a.any()或a.all()。@KeithJohnHutchison:您将按位和
&
与逻辑和
混淆了。使用
news['contain1']==0和news['contain2']==0和news['contain3']==0
Related:,只需将其替换为
df[columns].eq(0).all()
或u可以这样做:df.loc[~df.sum(axis=1).eq(0)]。。。减少了删除列或获取索引的需要。只是一个建议
df = news[news.ne(0).any(axis=1)]
#cols = ['contain1','contain2','contain3']
#if necessary filter only columns by list
#df = news[news[cols].ne(0).any(axis=1)]
print (df)
   contain1  contain2  contain3
0         1         0         0
2         0         1         1
3         1         0         1
5         1         1         1
print (news.ne(0))
   contain1  contain2  contain3
0      True     False     False
1     False     False     False
2     False      True      True
3      True     False      True
4     False     False     False
5      True      True      True

print (news.ne(0).any(axis=1))
0     True
1    False
2     True
3     True
4    False
5     True
dtype: bool