重组Pandas Dataframe

eqoofvh9  于 2022-11-20  发布在  其他
关注(0)|答案(1)|浏览(144)

如何创建此 Dataframe :

datecreated  timestamp  value  
2022-11-15      1       4000
2022-11-15      2       3900
2022-11-15      3       3850
2022-11-15      4       3810
2022-11-15      5       3790

变成:

datecreated     1     2     3     4     5
0   2022-11-15      4000  3900  3850  3810  3790

我试探着:

df = df.pivot(index='datecreated', columns='timestamp', values='value')

结果为:

timestamp       1       2       3       4      5
datecreated                                                                  
2022-11-15      4000    3900    3850    3810   3790

重设索引:

timestamp datecreated       1       2       3  ...
0         2022-11-15        4000.0  3900.0  3850.0...
sgtfey8w

sgtfey8w1#

您所看到的只是由于透视而将列的轴名称自动设置为timestamp

out = (df.pivot(index='datecreated', 
                columns='timestamp', 
                values='value')
         .reset_index()
         .rename_axis(columns=None))
print(out)

输出量:

datecreated     1     2     3     4     5
0  2022-11-15  4000  3900  3850  3810  3790

相关问题