Pivot a dataframe to make specific dates that were in columns become rows

60 Views Asked by At

I have a dataframe that has dates as most of the columns with the following structure:

df1 = pd.DataFrame({'State':['NY', 'CA'], '3/1/20' :[5, 10], '3/2/20': [11, 13], '3/3/20': [4, 12]})

and I want to 'pivot' the dataframe so it is now in this format:

df2 = pd.DataFrame({'Date':['3/1/20','3/1/20','3/2/20','3/2/20','3/3/20','3/1/20'], 'State':['NY', 'CA', 'NY', 'CA','NY', 'CA'], 'Values':[5,10,11,13,4,12]})

Does anyone have any suggestions on how to do this? Thanks!

1

There are 1 best solutions below

0
On BEST ANSWER

Use pd.melt

df2 = pd.melt(df1, id_vars=['State']).rename(columns={'variable':'Date','value':'number'})