I’m very new to python and pandas. I’m working with a dataframe where the data looks like this:
Location | Jan-22 | Feb-22 | Mar-22 |
---|---|---|---|
A | 1 | 2 | 3 |
B | 4 | 5 | 6 |
And I’m trying to convert the headers into values within a new column and then create a new row with the cell value. For example I’d like it to look like this:
Location | Value | Date |
---|---|---|
A | 1 | Jan-22 |
A | 2 | Feb-22 |
A | 3 | Mar-22 |
B | 4 | Jan-22 |
B | 5 | Feb-22 |
B | 6 | Mar-22 |
Any help would be appreciated. I’m still stuck on trying to generate a new column with values based on other column headers.
Thanks!
0
Try using pd.DataFrame.melt
:
df.melt('Location', var_name='Date', value_name='Value')
Output:
Location Date Value
0 A Jan-22 1
1 B Jan-22 4
2 A Feb-22 2
3 B Feb-22 5
4 A Mar-22 3
5 B Mar-22 6