使用
pivot
reindex
对于添加错误列:
cols = ['h{:02d}'.format(x) for x in range(1, 7)]
df = (df.pivot('author','hour','number_of_topics')
.fillna(0)
.reindex(columns=cols, fill_value=0)
.reset_index()
.rename_axis(None, axis=1))
print (df)
author h01 h02 h03 h04 h05 h06
0 A 1 0 0 0 8 0
1 B 0 4 0 2 0 0
2 C 0 0 0 6 3 0
或者
set_index
具有
unstack
:
cols = ['h{:02d}'.format(x) for x in range(1, 7)]
df = (df.set_index(['author','hour'])['number_of_topics']
.unstack(fill_value=0)
.reindex(columns=cols, fill_value=0)
.reset_index()
.rename_axis(None, axis=1))
print (df)
author h01 h02 h03 h04 h05 h06
0 A 1 0 0 0 8 0
1 B 0 4 0 2 0 0
2 C 0 0 0 6 3 0