【问题标题】:Rename the column's entries and then groupby in pandas重命名列的条目,然后在 pandas 中分组
【发布时间】:2018-01-14 08:39:33
【问题描述】:

假设我必须有两个名为“country_to_country”和“country_area_mapping”的数据框,如下所示。

>>> country_to_country
  From  To  Volume
0   c1  c4      10
1   c2  c5      20
2   c3  c6      30

>>> country_area_mapping
  Country  Area
0   c1     a1
1   c2     a2  
2   c3     a1  
3   c4     a2  
4   c5     a1  
5   c6     a2

预期的输出是:

  From  To  Volume
0   a2  a1      40
1   a2  a1      20

应将国家名称替换为相应的地区,然后使用 Volume 列上的 sum 对表格进行分组。

我的方法是对“From”列使用“merge”两次,然后将结果合并到“To”列。最后,应用“groupby”对相同的 From-To 区域体积求和。 但是,我觉得有一种更短的方法可以做到这一点。有什么替代方案的建议吗?

【问题讨论】:

    标签: python pandas dataframe pandas-groupby


    【解决方案1】:

    您可以使用DataFrame.replace by Series,然后使用groupby 聚合sum

    s = country_area_mapping.set_index('Country')['Area']
    df = country_to_country.replace({'From':s, 'To':s})
                           .groupby(['From','To'], as_index=False)['Volume'].sum()
    print (df)
      From  To  Volume
    0   a1  a2      40
    1   a2  a1      20
    

    【讨论】:

      【解决方案2】:

      创建映射:

      In [62]: mapping = dict(country_area_mapping[['Country', 'Area']].values)
      

      显式索引是为了保证生成映射时的顺序。现在使用df.replace,后跟df.groupby

      In [64]: country_to_country.replace(mapping).groupby(['From', 'To'], as_index=False).sum()
      Out[64]: 
        From  To  Volume
      0   a1  a2      40
      1   a2  a1      20
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-04-24
        • 2017-03-05
        • 2019-08-21
        • 2018-08-23
        • 2021-01-17
        • 2019-04-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多