如何转换结果Pandas。群比

2024-03-28 18:33:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经创建了一个分组数据框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无效。你知道吗


Tags: 数据id格式时间totaldurationweek雇员
2条回答

我想你需要^{}如果dfDataFrame 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

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')

相关问题 更多 >