Reshaping Dataframe using Pandas in Python

Viewed 47

I have the following data in a .csv file:

Original Format

I need to reshape the above mentioned data into the following format:

Required Format

Can someone kindly explain how can I do that? I have an idea it can be done using df.pivot() function, however, the dates are in the 'headings' of the original format, which is confusing me a bit.

I shall be grateful for the help.

Thank you

1 Answers

First, minimal data:

import numpy as np
df=pd.DataFrame({'Province/State':[np.nan], 'Country/region':['Afghanistan'], 'Lat':[0],'Long':[0],'1/22/20':[0],'1/23/20':[0],'6/23/20':[29640]})
print(df)



 Province/State Country/region  Lat  Long  1/22/20  1/23/20  6/23/20
0             NaN    Afghanistan    0     0        0        0    29640

Now let us pd.melt this

pd.melt(df, id_vars=['Province/State', 'Country/region'], value_vars=['1/22/20', '1/23/20','6/23/20'],var_name='Date', value_name='Confirmed')



 Province/State Country/region     Date  Confirmed
0             NaN    Afghanistan  1/22/20          0
1             NaN    Afghanistan  1/23/20          0
2             NaN    Afghanistan  6/23/20      29640
Related