python - 在 Pandas 数据框中的列子集中查找具有非零值的行

标签 python pandas dataframe

我有一个包含 4 列字符串和其他整数的数据框。现在我需要找出那些数据行,其中至少一列是非零值(或 > 0)。

manwra,sahAyaH,T7,0,0,0,0,T
manwra, akriti,T5,0,0,1,0,K 
awma, prabrtih,B6, 0,1,1,0,S

我的输出应该是

manwra, akriti,T5,0,0,1,0,K 
awma, prabrtih,B6, 0,1,1,0,S

我尝试了以下方法来获得答案。字符串值位于第 0、1、2 和 -1 列(最后一列)。

KT[KT.ix[:,3:-2] != 0]

我收到的输出是

NaN,NaNNaN,NaN,NaN,NaN,NaN,NaN
NaN,NaN,NaN,NaN,NaN,1,NaN,NaN
NaN,NaN,NaN,NaN,1,1,NaN,NaN

如何获得想要的输出

最佳答案

这是一个使用 select_dtypes() 的替代解决方案方法:

In [41]: df[(df.select_dtypes(include=['number']) != 0).any(1)]
Out[41]:
        0          1   2  3  4  5  6  7
1  manwra     akriti  T5  0  0  1  0  K
2    awma   prabrtih  B6  0  1  1  0  S

解释:

In [42]: df.select_dtypes(include=['number']) != 0
Out[42]:
       3      4      5      6
0  False  False  False  False
1  False  False   True  False
2  False   True   True  False

In [43]: (df.select_dtypes(include=['number']) != 0).any(1)
Out[43]:
0    False
1     True
2     True
dtype: bool

关于python - 在 Pandas 数据框中的列子集中查找具有非零值的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39187788/

相关文章:

python - 基于带有日期索引的 bool 系列过滤 pandas DataFrame?

R:创建一个变量,该变量使用 for 循环中前一行的值

python Pandas : Modify Dataframe with mask and create new Dataframe

python - 警告 :tensorflow:Ignoring detection with image id despite true config parameters

python - Modbus 从站不响应

Python subprocess.Popen 通过管道进行通信

python - 数组维度大小为 3 时的混淆矩阵错误

python - Pandas:使用方法链修改单元格值

python - 如何克服 'ValueError: Wrong number of items passed 2, placement implies 1'错误?

python - 如何在执行 df.groupby 时在 groupby 列之一中保留 null/nan