python - 熊猫中多列的逻辑与
问题描述
我有一个数据框(edata),如下所示
Domestic Catsize Type Count
1 0 1 1
1 1 1 8
1 0 2 11
0 1 3 14
1 1 4 21
0 1 4 31
从这个数据帧我想计算所有计数的总和,其中两个变量(国内和 Catsize)的逻辑与导致零(0),使得
1 0 0
0 1 0
0 0 0
我用来执行该过程的代码是
g=edata.groupby('Type')
q3=g.apply(lambda x:x[((x['Domestic']==0) & (x['Catsize']==0) |
(x['Domestic']==0) & (x['Catsize']==1) |
(x['Domestic']==1) & (x['Catsize']==0)
)]
['Count'].sum()
)
q3
Type
1 1
2 11
3 14
4 31
此代码工作正常,但是,如果数据框中的变量数量增加,则条件数量会迅速增长。那么,是否有一种聪明的方法来编写一个条件,即如果两个(或更多)变量的 AND 运算结果为零,则执行 sum() 函数
解决方案
pd.DataFrame.all
您可以先使用否定过滤:
cols = ['Domestic', 'Catsize']
res = df[~df[cols].all(1)].groupby('Type')['Count'].sum()
print(res)
# Type
# 1 1
# 2 11
# 3 14
# 4 31
# Name: Count, dtype: int64