Pandas中具有重复索引且没有聚合函数的数据透视表



我有一个数据帧:

device_id   timestamp             metric_id    value
0   device_1    2020-12-04 05:15:00   cpu_5min      116
1   device_1    2020-12-04 05:30:00   cpu_5min      213
2   device_1    2020-12-04 05:35:00   cpu_5min      427
3   device_1    2020-12-04 05:15:00   vol_max       734
4   device_1    2020-12-04 05:30:00   vol_max       325
5   device_1    2020-12-04 05:35:00   vol_max       668
6   device_2    2020-12-04 05:15:00   cpu_5min      540
7   device_2    2020-12-04 05:30:00   cpu_5min      127
8   device_2    2020-12-04 05:35:00   cpu_5min      654

我需要将此表调整为如下所示:

device_id   timestamp              cpu_5min   vol_max
0   device_1    2020-12-04 05:15:00      116        734
1   device_1    2020-12-04 05:30:00      213        325
2   device_1    2020-12-04 05:35:00      427        668
3   device_2    2020-12-04 05:15:00      540        NA
4   device_2    2020-12-04 05:30:00      127        NA
5   device_2    2020-12-04 05:35:00      654        NA

因此,所有唯一的metric_id都将作为新的标头进行透视,并具有各自的值。如果不存在任何值,则在那里放置NA。

我已经查看了SO上的其他枢轴答案,但它们似乎都假设了聚合函数和/或非重复索引。

请尝试

pd.pivot_table(df, index=['device_id','timestamp'], columns=['metric_id']).droplevel(0, axis=1).reset_index()

最新更新