您可以使用reindex
新Multindex
創建from_product
:
注意:
What is the difference between size and count in pandas?
df = pd.DataFrame({
'month': [0, 0, 0, 0, 1, 1, 1, 2, 2, 7],
'code': ['s_A', 's_A', 's_A', 's_A', 's_A', 's_A', 's_A', 's_B', 's_B', 's_B'],
'id': ['sally1','sally1','sally1','sally','sally','sally','sally','sally','sally','sally']})
print (df)
code id month
0 s_A sally1 0
1 s_A sally1 0
2 s_A sally1 0
3 s_A sally 0
4 s_A sally 1
5 s_A sally 1
6 s_A sally 1
7 s_B sally 2
8 s_B sally 2
9 s_B sally 7
df = df.groupby(['id', 'code', 'month']).size()
n = ['id','code','month']
mux = pd.MultiIndex.from_product([df.index.levels[0],df.index.levels[1], range(13)], names=n)
df = df.reindex(mux, fill_value=0)
print (df)
id code month
sally s_A 0 1
1 3
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
10 0
11 0
12 0
s_B 0 0
1 0
2 2
3 0
...
...
舊的解決方案:
reindex
與unstack
和stack
,但後來需要一些數據清洗:
df = df.groupby(['id', 'code', 'month']).size() \
.to_frame('count') \
.unstack([0,1], fill_value=0) \
.reindex(range(13), fill_value=0) \
.stack([1,2], dropna=False) \
.fillna(0) \
.astype(int) \
.swaplevel(0,2) \
.sort_index()
print (df)
count
code id month
s_A sally 0 1
1 3
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
10 0
11 0
12 0
sally1 0 3
1 0
2 0
3 0
4 0
你沒有表現出@splinter我更新了''m''列 – splinter
。 m是月。 – planaria