【问题标题】:Pandas: How to group multiple row by different criteria熊猫:如何按不同的标准对多行进行分组
【发布时间】:2021-09-10 09:21:04
【问题描述】:

我正在尝试按不同条件对行进行分组,示例如下。基本上,我想尝试的是将Team 名称分组,并将其放入一个新的Dataframesum of goal。我试过groupby,但不知何故不能做我想做的事。我怎样才能得到预期的结果?谢谢!

example = {'Team':['Arsenal', 'Manchester United', 'Arsenal',
               'Arsenal', 'Chelsea', 'Manchester United',
               'Manchester United', 'Chelsea', 'Chelsea', 'Chelsea',
               'Juventus','Juventus'],
                 
       'Player':['Ozil', 'Pogba', 'Lucas', 'Aubameyang',
                   'Hazard', 'Mata', 'Lukaku', 'Morata', 
                                     'Giroud', 'Kante',
                'Ronaldo','Buffon'],
                                       
       'Goals':[5, 3, 6, 4, 9, 2, 0, 5, 2, 3, 20, 0] }
group_dict = {'UK':['Arsenal', 'Manchester United', 'Chelsea'], 'Italy':['Juventus']}

预期结果:

Country    Goals
UK          39
Italy       20

【问题讨论】:

    标签: python pandas dataframe group-by


    【解决方案1】:

    创建一个字典,从Team 反向映射到Country,然后通过Country 聚合:

    df = pd.DataFrame(example)
    
    df.Goals.groupby(
      df.Team.map({v: k for k, lst in group_dict.items() for v in lst}).rename('Country')
    ).sum().reset_index()
    
    #  Country  Goals
    #0   Italy     20
    #1      UK     39
    

    【讨论】:

    • 谢谢!但是如果我有不止一列要总结怎么办?比如Goals1、Goals_yesterday、Goals_last_month?
    • 您可以通过df[['Goals1', 'Goals_yesterday', 'Goals_last_month']].groupby(...).sum(...)...对所有列求和
    【解决方案2】:

    您可以使用np.select 临时分配一个新列为contry 然后groupby contry 并调用sum

    df.assign(contry=np.select([df['Team'].isin(v) for v in group_dict.values()],
                list(group_dict.keys()),
                '')).groupby('contry', sort=False, as_index=False)['Goals'].sum()
    

    输出:

      contry  Goals
    0     UK     39
    1  Italy     20
    

    【讨论】:

    • 如果我有不止一列要总结?比如Goals1、Goals_yesterday、Goals_last_month?只需将它们放在最后一个 ['Goals'] 中?
    • 是的,您可以将它们作为列表@WILLIAM
    猜你喜欢
    • 1970-01-01
    • 2013-11-16
    • 2022-12-12
    • 2016-02-02
    • 2020-08-10
    • 2021-07-20
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    相关资源
    最近更新 更多