enter image description here我正在尝试重塑如下所示的数据框:
enter image description here我想重塑我的数据框,使其看起来像这样:
您可以结合使用melt和pivot_table。融化会将国家/地区列放入行,然后数据透视表将为您提供所需的结果。
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