我有一个数据帧:
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
我已经看了SO上的其他pivot答案,但它们似乎都假定有一个聚合函数和/或非重复索引。
请尝试一下
pd.pivot_table(df, index=['device_id','timestamp'], columns=['metric_id']).droplevel(0, axis=1).reset_index()