熊猫中多列的逻辑与

esh*_*mad 5 python numpy dataframe python-3.x pandas

我有一个如下所示的数据框(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
Run Code Online (Sandbox Code Playgroud)

从这个数据框中,我想计算所有计数的总和,其中两个变量(国内和 Catsize)的逻辑 AND 结果为零(0),使得

1   0    0
0   1    0
0   0    0
Run Code Online (Sandbox Code Playgroud)

我用来执行这个过程的代码是

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
Run Code Online (Sandbox Code Playgroud)

这段代码工作正常,但是,如果数据帧中的变量数量增加,则条件数量会迅速增加。那么,是否有一种聪明的方法来编写一个条件,说明如果两个(或多个)变量的 AND 运算结果为零,则执行 sum() 函数

jpp*_*jpp 5

您可以首先使用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
Run Code Online (Sandbox Code Playgroud)


cs9*_*s95 4

用于np.logical_and.reduce概括。

columns = ['Domestic', 'Catsize']
df[~np.logical_and.reduce(df[columns], axis=1)].groupby('Type')['Count'].sum()

Type
1     1
2    11
3    14
4    31
Name: Count, dtype: int64
Run Code Online (Sandbox Code Playgroud)

在将其添加回来之前,请使用map广播:

u = df[~np.logical_and.reduce(df[columns], axis=1)].groupby('Type')['Count'].sum()
df['NewCol'] = df.Type.map(u)

df
   Domestic  Catsize  Type  Count  NewCol
0         1        0     1      1       1
1         1        1     1      8       1
2         1        0     2     11      11
3         0        1     3     14      14
4         1        1     4     21      31
5         0        1     4     31      31
Run Code Online (Sandbox Code Playgroud)