gpt4 book ai didi

python - 使用 pandas python 聚合数据

转载 作者:行者123 更新时间:2023-11-30 22:02:12 25 4
gpt4 key购买 nike

我有以下类似的数据:

表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")

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

访问结果表的最合适方法是什么?

提前谢谢您。

最佳答案

使用 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

关于python - 使用 pandas python 聚合数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53858086/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com