gpt4 book ai didi

python Pandas : replace groupby operation

转载 作者:太空宇宙 更新时间:2023-11-04 09:34:11 24 4
gpt4 key购买 nike

我将下表作为 pandas 数据框:

| ID | Name | Sales | Source   |
|----|------|-------|----------|
| 1 | a | 34 | Source A |
| 2 | b | 3423 | Source A |
| 3 | c | 2 | Source A |
| 4 | d | 342 | Source A |
| 3 | c | 34 | Source A |
| 5 | e | 234 | Source A |
| 6 | f | 234 | Source A |
| 7 | g | 23 | Source A |
| 1 | a | 12 | Source B |
| 2 | b | 42 | Source B |
| 3 | c | 9 | Source B |
| 2 | b | 22 | Source B |
| 1 | a | 1 | Source B |
| 8 | h | 56 | Source B |

最好的方法是 (i) 汇总每个源的每个 ID 的销售额,以及 (ii) 将结果放入两个新列“Source A”和“Source B”,这样生成的 dataframe 看起来如下:

| ID | Name | Source A | Source B |
|----|------|----------|----------|
| 1 | a | 34 | 13 |
| 2 | b | 3423 | 64 |
| 3 | c | 36 | 9 |
| 4 | d | 342 | 0 |
| 5 | e | 234 | 0 |
| 6 | f | 234 | 0 |
| 7 | g | 23 | 0 |
| 8 | h | 0 | 56 |

我最初的做法如下:

data = {"ID":[1,2,3,4,3,5,6,7,1,2,3,2,1,8], 
"Name":list("abcdcefgabcbah"),
"Sales":[34,3423,2,342,34,234,234,23,12,42,9,22,1,56],
"Source":["Source A"]*8 + ["Source B"]*6
}
df = pd.DataFrame(data)

df.groupby(["ID","Name","Source"])["Sales"].sum().unstack()

问题:我的初始表是使用不同的文件构建的,而不是应用 pd.concat。所以感觉我可以通过首先以不同方式连接(或合并)来实现最终表。有没有更好的方法来实现这一目标?作为侧节点:实际数据表由 6 个不同的来源组成。

感谢您的帮助!

最佳答案

你可以使用pd.crosstab:

pd.crosstab(df.Name, df.Source, df.Sales, aggfunc='sum').fillna(0)

输出:

Source  Source A  Source B
Name
a 34.0 13.0
b 3423.0 64.0
c 36.0 9.0
d 342.0 0.0
e 234.0 0.0
f 234.0 0.0
g 23.0 0.0
h 0.0 56.0

或者,数据透视表

df.pivot_table('Sales','Name','Source', aggfunc='sum').fillna(0)

输出:

Source  Source A  Source B
Name
a 34.0 13.0
b 3423.0 64.0
c 36.0 9.0
d 342.0 0.0
e 234.0 0.0
f 234.0 0.0
g 23.0 0.0
h 0.0 56.0

或者使用 set_indexsumlevel 参数,然后 unstack:

df.set_index(['Name','Source'])['Sales'].sum(level=[0,1]).unstack(fill_value=0) 

输出:

Source  Source A  Source B
Name
a 34 13
b 3423 64
c 36 9
d 342 0
e 234 0
f 234 0
g 23 0
h 0 56

关于 python Pandas : replace groupby operation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54447477/

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