Problem
在 pandas groupby 聚合的输出中包括所有可能的值或值的组合。
Example
示例 pandas DataFrame 有三列,User
, Code
, and Subtotal
:
import pandas as pd
example_df = pd.DataFrame([['a', 1, 1], ['a', 2, 1], ['b', 1, 1], ['b', 2, 1], ['c', 1, 1], ['c', 1, 1]], columns=['User', 'Code', 'Subtotal'])
我想加个群User
and Code
并获得每个组合的小计User
and Code
.
print(example_df.groupby(['User', 'Code']).Subtotal.sum().reset_index())
我得到的输出是:
User Code Subtotal
0 a 1 1
1 a 2 1
2 b 1 1
3 b 2 1
4 c 1 2
我怎样才能包含缺少的组合User=='c'
and Code==2
在表中,即使它不存在于example_df
?
首选输出
下面是首选输出,其中零线表示User=='c'
and Code==2
组合。
User Code Subtotal
0 a 1 1
1 a 2 1
2 b 1 1
3 b 2 1
4 c 1 2
5 c 2 0