我正在研究如何计算符合某些条件的特定列的数量并过滤上述 1 中的任何列。我认为这需要添加一个包含
count()
的附加列,然后执行一个单独的步骤来查看是否count()
大于1。最后,删除不必要的count()
列。
对于下面的示例,我只对大于 0 的 colB、colC、colD 和 colE 感兴趣。
我尝试过的示例尝试代码如下所示:
#Step a
filtData['countCol'] = filtData[(filtData['colB']>0) & (filtData['colC']>0) &
(filtData['colD']>0) & (filtData['colE']>0)].count()
#Step b
filtData['countCol'] = filtData[filtData['countCol'] > 1]
#Step c
filtData = filtData.drop(columns=['countCol'])
输入:
colA colB colC colD colE colF
0 1105 0.00 867 3.4 0.00 text1
1 1106 3 3.22 1 3 text2
2 1107 0.5 0 0 1 text3
3 1110 0 23 0 0 text4
4 1019 9 0.0 2 0 text5
5 1267 0 0.0 0 2 text6
输出步骤a:
colA colB colC colD colE colF countCol
0 1105 0.00 867 3.4 0.00 text1 2
1 1106 3 3.22 1 3 text2 4
2 1107 0.5 0 0 1 text3 2
3 1110 0 23 0 0 text4 1
4 1019 9 0.0 2 0 text5 2
5 1267 0 0.0 0 2 text6 1
输出步骤b:
colA colB colC colD colE colF countCol
0 1105 0.00 867 3.4 0.00 text1 2
1 1106 3 3.22 1 3 text2 4
2 1107 0.5 0 0 1 text3 2
4 1019 9 0.0 2 0 text5 2
输出步骤c:
colA colB colC colD colE colF
0 1105 0.00 867 3.4 0.00 text1
1 1106 3 3.22 1 3 text2
2 1107 0.5 0 0 1 text3
4 1019 9 0.0 2 0 text5
如果有一种方法可以优雅地一步执行此操作(不是太高级的表达式难以理解),那将是理想的。我仍在学习 pandas,所以也许执行我正在寻找的过滤需要在所示的三个子步骤中进行打破。
用途:
out = filtData[(filtData[['colB','colC','colD','colE']]>0).sum(axis=1) > 1]
print (out)
colA colB colC colD colE colF
0 1105 0.0 867.00 3.4 0.0 text1
1 1106 3.0 3.22 1.0 3.0 text2
2 1107 0.5 0.00 0.0 1.0 text3
4 1019 9.0 0.00 2.0 0.0 text5