Reputation: 602
I have a data frame in python and I want to convert in different format :
Below is the example of the same :
Current Data frame :
Header 1 Header 1
Col_A Col_B Col_A Col_B
2021-07-15 1 2 3 4
2021-07-16 5 6 7 8
Expected Output :
Date Header_No Col_A Col_B
2021-07-15 1 1 2
2021-07-16 1 5 6
2021-07-15 2 3 4
2021-07-16 2 7 8
Basically I want 4 columns Date , Header_No , Col_A, Col_B.
Upvotes: 1
Views: 40
Reputation: 11395
That’s literally what .stack()
does:
Stack the prescribed level(s) from columns to index.
With some tweaking to rename columns as you want to and from index levels and/or columns:
>>> stacked = df.rename(columns=lambda c: int(c.split()[-1]), level=0).stack(level=0)
>>> stacked
Col_A Col_B
2021-07-15 1 1 2
2 3 4
2021-07-16 1 5 6
2 7 8
>>> stacked.rename_axis(['Date', 'Header_No']).reset_index()
Date Header_No Col_A Col_B
0 2021-07-15 1 1 2
1 2021-07-15 2 3 4
2 2021-07-16 1 5 6
3 2021-07-16 2 7 8
Upvotes: 1