Regrouping pandas dataframe

Question:

How can I make this 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

to become:

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

I tried:

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

and the result is:

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

Reset index:

timestamp datecreated       1       2       3  ...
0         2022-11-15        4000.0  3900.0  3850.0...
Asked By: Leb_Broth

||

Answers:

What you’re seeing is just the column’s axis name being automatically set to timestamp because of your pivot. This can be remedied by renaming the axis:

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

Output:

  datecreated     1     2     3     4     5
0  2022-11-15  4000  3900  3850  3810  3790
Answered By: BeRT2me
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.