-3

I am trying to remodel my dataframe that looks like this:

enter image description here

I would like to reshape my dataframe to look like this:

enter image description here

Matt Hall
  • 7,614
  • 1
  • 23
  • 36

2 Answers2

1

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']]
Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41
0

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

Sample result: enter image description here

jose_bacoy
  • 12,227
  • 1
  • 20
  • 38