I am trying to remodel my dataframe that looks like this:
I would like to reshape my dataframe to look like this:
I am trying to remodel my dataframe that looks like this:
I would like to reshape my dataframe to look like this:
Use the following code:
s = df.set_index(['Year', 'Measure']).stack()
s.index.names = ['Year', 'Measure', 'Country']
df2 = s.unstack(level=1).reset_index()
df2.columns.name = None
df2 = df2[['Year', 'Country', 'Population', 'GDP']]
You can combine melt and pivot_table. Melt will put the country columns into rows then pivot table will give you the desired result.
df = pd.DataFrame.from_dict({'Year': [1870, 1870, 1871, 1871, 1872, 1872],
'Measure': ['Population', 'GDP', 'Population', 'GDP', 'Population', 'GDP'],
'Australia': [187, 870, 181, 11, 172, 72],
'Belgium': [ 181, 11, 172, 72, 187, 870,],
'Denmark': [187, 870,187, 870,187, 870,]})
df = df.melt(id_vars=["Year", "Measure"], var_name="Country", value_name="Value")
df = df.pivot_table('Value', ['Year','Country'], 'Measure').reset_index().rename_axis(None, axis=1)
df