【问题标题】:Nested groupby using Pandas使用 Pandas 嵌套 groupby
【发布时间】:2022-11-04 00:55:43
【问题描述】:

我想将美国、中国和日本的能源值相加,并将其标记为“group1” 然后按日期、国家、类型和能量值进行分组。

数据

我们按日期和类型分组并取这些特定国家/地区的总和:美国、中国和日本 - 将此组合重命名为 group1

date        country    type energy
8/1/2022    US         aa   10
8/1/2022    US         aa   11
8/1/2022    China      bb   50
8/1/2022    Japan      bb   20
10/1/2022   Australia  bb   5
                    

期望的

date        country   type  energy
8/1/2022    group1    aa    21
8/1/2022    group1    bb    70
10/1/2022   Australia bb    5

正在做

df.groupby(['country','date', 'type'], as_index=False).agg({'energy': sum})

上面的脚本完美地执行了 groupby 和 sum,但在执行此步骤之前不确定如何将某些类别浓缩到一个组中。

任何建议表示赞赏

【问题讨论】:

    标签: python pandas numpy group-by


    【解决方案1】:

    如果你想组合它们,那么首先过滤并将值更改为group1然后进行groupby怎么样?

    df.loc[df['country'].isin(['US', 'China', 'Japan']), 'country'] = 'group1'
    df.groupby(['date', 'type', 'country'], as_index=False, sort=False).agg({'energy': sum})
    
            date type    country  energy
    0   8/1/2022   aa     group1      21
    1   8/1/2022   bb     group1      70
    2  10/1/2022   bb  Australia       5
    

    【讨论】:

      【解决方案2】:
      # define a dictionary to group the countries
      d={'US': 'Group-1',
         'China':'Group-1',
         'Japan' :'Group-1'}
      
      # create a group column, based on mapping
      # keeping a separate column, to avoid losing original values
      # it can very well be a country
      df['group']=df['country'].map(d).fillna(df['country'])
      
      # do a groupby
      out= df.groupby(['group','date', 'type'], as_index=False).agg({'energy': sum})
      
      
      
      
      
          group           date    type    energy
      0   Australia   10/1/2022   bb      5
      1   Group-1     8/1/2022    aa     21
      2   Group-1     8/1/2022    bb     70
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-14
        • 2021-12-10
        • 2015-08-02
        • 1970-01-01
        • 2021-08-06
        • 2016-04-16
        • 2014-11-28
        • 1970-01-01
        相关资源
        最近更新 更多