【问题标题】:How to groupby with conditions in pandas?如何根据熊猫的条件分组?
【发布时间】:2021-08-27 01:57:04
【问题描述】:

我有一张如下表

date train condition 1 condition 2
day1 1111 true 0
day2 2222 false 2

.....

我想将火车与日期分组,

date train total count train with condition 1 is true train with condition 2 > 0 train with condition 1 true and condition 2>0
day1 1 1 0 0
day2 1 0 1 0

如何使用 pandas 实现这一目标?

【问题讨论】:

    标签: pandas dataframe group-by


    【解决方案1】:

    为了提高性能比较 greater like 0 在 groupby 到帮助列之前,然后聚合 countsum 以计数 Trues 值在 named aggregation 中,对于带有空格的新列名称使用 @ 987654327@解包技巧:

    df1 = (df.assign(new = df['condition 2'].gt(0))
             .groupby('date')
             .agg(**{'train total count': ('train', 'count'), 
                     'train with condition 1 is true': ('condition 1','sum'), 
                     'train with condition 2 > 0':('new','sum')})
             .reset_index())
    
    print (df1)
       date  train total count  train with condition 1 is true  \
    0  day1                  1                               1   
    1  day2                  1                               0   
    
       train with condition 2 > 0  
    0                           0  
    1                           1  
    

    【讨论】:

    • agg(**)是什么意思?
    • 为什么 agg 需要 **?
    • 其实我找到了如果你想要的输出列名不是有效的Python关键字,构造一个字典,解压关键字参数。
    • 如果我们在这里想要多个条件怎么办?
    【解决方案2】:

    您可以使用 .agg() 方法为不同的列应用不同的聚合。

    试试这个:

    df.groupby('date').agg({'train':'count',
                            'condition 1':'sum', 
                            'condition 2': lambda x: (x>0).sum()})
    

    输出:

           train    condition 1   condition 2
    date            
    day1     1           1             0
    day2     1           0             1
    

    请注意,如果condition 1 是一个布尔列,python 在求和时将True 视为1False 视为0

    【讨论】:

      【解决方案3】:
       Print (df)
      
         date  train  condition 1  condition 2
      0  day1   1111         True            0
      1  day2   2222        False            2
      
      
      
      df['condition 1']=df['condition 1'].astype(int)
      

      让我们试试 groupby agg

      df.groupby('date').agg(traintotalcount=('train', 'count'), trainwithcondition1istrue=('condition 1', lambda x: x.astype(int)), trainwithcondition2gt0=('condition 2', lambda x: int(x>0)))
      

      结果

            traintotalcount  trainwithcondition1istrue  trainwithcondition2gt0
      date                                                                    
      day1                1                          1                       0
      day2                1                          0                       1
      

      【讨论】:

        【解决方案4】:

        通过groupby()agg() 方法尝试:

        out=(df.groupby('date',as_index=False)
               .agg(
                   {'train':'count','condition 1':lambda x:x,'condition 2':lambda x:x.gt(0)}
                   )
             )
        

        最后使用astype()方法:

        out[['condition 1','condition 2']]=out[['condition 1','condition 2']].astype(int)
        

        out的输出:

            date    train   condition 1     condition 2
        0   day1    1       1                   0
        1   day2    1       0                   1
        

        如果需要更改列的名称,请使用:

        out.columns=['date','train total count','train with condition 1 is true','train with condition 2']
        

        【讨论】:

          猜你喜欢
          • 2022-01-25
          • 2021-07-06
          • 2016-12-25
          • 2020-01-25
          • 2018-05-24
          • 2019-11-03
          • 2020-04-05
          • 1970-01-01
          • 2021-11-10
          相关资源
          最近更新 更多