麻烦是这个。
假设我们有一个可以使用以下方法生成的 Pandas df:
month=['dec','dec','dec','jan','feb','feb','mar','mar']
category =['a','a','b','b','a','b','b','b']
sales=[1,10,2,5,12,4,3,1]
df = pd.DataFrame(list(zip(month,category,sales)),
columns =['month', 'cat','sales'])
print(df)
| month cat sales |
|--------------------|
| 0 dec a 1 |
| 1 dec a 10 |
| 2 dec b 2 |
| 3 jan b 5 |
| 4 feb a 12 |
| 5 feb b 4 |
| 6 mar b 3 |
| 7 mar b 1 |
那么让我们假设我们想按月计算每个类别。
所以我们去做类似的事情
df=df.groupby(['month','cat']).sales.sum().reset_index()
print(df)
| month cat sales |
|--------------------|
| 0 dec a 11 |
| 1 dec b 2 |
| 2 feb a 12 |
| 3 feb b 4 |
| 4 jan b 5 |
| 5 mar b 4 |
但我们希望看到的是:
| month cat sales |
|--------------------|
| 0 dec a 11 |
| 1 dec b 2 |
| 2 feb a 12 |
| 3 feb b 4 |
| 4 jan b 5 |
| 5 jan a 0 |
| 6 mar b 4 |
| 7 mar a 0 |
不同之处在于在特定月份没有出现的类别仍然会以零作为总数出现。
之前可能有人问过这个问题,但我找不到。如果您指出问题的方向,我们将继续删除此问题。
最佳答案
从您停下的地方继续,stack 的组合和 unstack会给你你需要的输出:
res = (df.groupby(['month','cat'])
.sales
.sum()
#unstack and fill value for the null column
.unstack(fill_value=0)
#return to groupby form and reset
.stack()
.reset_index(name='sales')
)
res
month cat sales
0 dec a 11
1 dec b 2
2 feb a 12
3 feb b 4
4 jan a 0
5 jan b 5
6 mar a 0
7 mar b 4
关于python - 返回组中所有唯一的聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61535744/