2024-03-28 18:33:45 发布
网友
我已经创建了一个分组数据框total_hours,按雇员id和他们每个人的总工作时间week
total_hours
id
week
id week duration 4 35 7.000000 36 2.000000 ... ... 40 5.000000
如何将结果转换为以下格式?你知道吗
id 35 36 37 38 39 40 4 7.0 2.0 7.0 2.0 4.0 5.0
我试过total_hours.T,但对SeriesGroupBy无效。你知道吗
total_hours.T
SeriesGroupBy
我想你需要^{}如果df是DataFrame with MultiIndex:
df
DataFrame with MultiIndex
#e.g. possible created df df = df.groupby(['id', 'week']).sum() print (df.index) MultiIndex([(4, 35), (4, 36), (4, 40)], names=['id', 'week']) df1 = df['duration'].unstack() print (df1) week 35 36 40 id 4 7.0 2.0 5.0
如果需要id到列:
df1 = df['duration'].unstack().reset_index().rename_axis(None, axis=1) print (df1) id 35 36 40 0 4 7.0 2.0 5.0
另一种选择是如果需要聚合sum:
sum
df1 = df.pivot_table(index='id', columns='week', values='duration', aggfunc='sum') df1 = df1.reset_index().rename_axis(None, axis=1)
尝试使用以下选项:
df = df.pivot(index='id', columns='week', values='duration')
我想你需要^{} 如果
df
是DataFrame with MultiIndex
:如果需要
id
到列:另一种选择是如果需要聚合
sum
:尝试使用以下选项:
相关问题 更多 >
编程相关推荐