【问题标题】:Logical AND of multiple columns in pandas熊猫中多列的逻辑与
【发布时间】:2019-06-06 23:47:28
【问题描述】:

我有一个如下所示的数据框(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() 函数

【问题讨论】:

    标签: python python-3.x pandas numpy dataframe


    【解决方案1】:

    您可以先使用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
    

    【讨论】:

      【解决方案2】:

      使用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
      

      添加回来之前,使用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
      

      【讨论】:

      • 是否可以将logical_and 用于具有数值的变量。例如,如果 catsize 列具有诸如 0,2,4,5,6,8 之类的值?
      • @eshfaqahmad 先将列转换为布尔值:df[col]=df[col].astype(bool)
      • 非常感谢您的回复。我试过了,但这给了我一些错误KeyError: '[-1 -1 -2 -1 -2 -1 ] not in index。我已将“Catsize”列更改为“Legs”,并将值更改为 0,0,2,4,4,5。
      • @eshfaqahmad 嗨,我建议提出一个新问题。通过这种方式,您会更快地获得帮助。
      • 我在大约 3 天前已经提出了一个问题,但还没有答案或评论。
      【解决方案3】:

      怎么样

      columns = ['Domestic', 'Catsize']
      df.loc[~df[columns].prod(axis=1).astype(bool), 'Count']
      

      然后随心所欲地使用它。

      对于逻辑 AND,该产品可以很好地解决问题。 对于逻辑或您可以使用 sum(axis=1) 提前适当的否定。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-01-09
        • 2017-02-23
        • 1970-01-01
        • 1970-01-01
        • 2020-11-09
        • 2023-03-25
        相关资源
        最近更新 更多