返回组中所有唯一的聚合

bor*_*ked 6 python aggregation pandas pandas-groupby

麻烦是这个。

假设我们有一个可以使用以下方法生成的 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 |
Run Code Online (Sandbox Code Playgroud)

那么让我们假设我们想按月计算每个类别。

所以我们去做类似的事情

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 |
Run Code Online (Sandbox Code Playgroud)

但我们希望看到的是:

|  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 |
Run Code Online (Sandbox Code Playgroud)

不同之处在于在特定月份没有出现的类别仍然会以零作为总数出现。

之前可能有人问过这个问题,但我找不到。如果您指出问题的方向,我们将继续删除此问题。

sam*_*mmy 10

从您停止的地方继续,stackunstack的组合将为您提供所需的输出:

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
Run Code Online (Sandbox Code Playgroud)


San*_*apa 6

MultiIndexreindex作为一起使用:

df=(
    df.groupby(['month','cat']).sales.sum()
    .reindex(pd.MultiIndex.from_product([df.month.unique(), df.cat.unique()], 
                                   names=['month', 'cat']), fill_value=0)
    .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   a      0
5   jan   b      5
6   mar   a      0
7   mar   b      4
Run Code Online (Sandbox Code Playgroud)