【问题标题】:Aggregating data using pandas python使用 pandas python 聚合数据
【发布时间】:2019-05-20 08:24:06
【问题描述】:

我有如下类似的数据:

表 1

Colour  Make
Red     Ford
Blue    BMW
Blue    BMW
Green   Golf
Yellow  Audi
Yellow  Audi
Yellow  Audi

表 2

Colour  Make    Count
Green   Ford    5
Blue    BMW     1
Green   Golf    6
Orange  BMW     1

我想使用 pandas 来聚合表 1 中的数据,然后如果表 2 已经存在则增加计数,如果不存在则插入新记录。从上面的示例数据:

结果表:

Colour  Make    Count
Green   Ford    5
Blue    BMW     3
Green   Golf    7
Orange  BMW     1
Red     Ford    1
Yellow  Audi    3

要完成第一个聚合步骤,我有:

df1.groupby(["Colour", "Make"]).size()reset_index(name="Count")

但是,我不确定如何进行第二步。我倾向于选择某种基于循环的解决方案,但我读过这是一个禁忌。

到达结果表的最合适方法是什么?

提前谢谢你。

【问题讨论】:

    标签: python pandas aggregate pandas-groupby


    【解决方案1】:

    您可以对齐索引和结构,然后使用pd.DataFrame.addfill_value=0

    res = df1.groupby(['Colour', 'Make']).size().to_frame('Count')\
             .add(df2.set_index(['Colour', 'Make']), fill_value=0)\
             .astype(int).reset_index()
    
    print(res)
    
       Colour  Make  Count
    0    Blue   BMW      3
    1   Green  Ford      5
    2   Green  Golf      7
    3  Orange   BMW      1
    4     Red  Ford      1
    5  Yellow  Audi      3
    

    【讨论】:

      【解决方案2】:

      使用concatgroupby size

      pd.concat([df1.assign(Count=1),df2]).groupby(['Colour','Make']).Count.sum().reset_index()
      Out[127]: 
         Colour  Make  Count
      0    Blue   BMW      3
      1   Green  Ford      5
      2   Green  Golf      7#check you expected output at this line 
      3  Orange   BMW      1
      4     Red  Ford      1
      5  Yellow  Audi      3
      

      【讨论】:

      • 使用 .Count 时出现错误。我已替换为 ["Count"],它按预期工作。
      猜你喜欢
      • 2017-01-27
      • 2014-08-28
      • 2014-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-23
      • 1970-01-01
      • 2021-01-22
      相关资源
      最近更新 更多