我曾尝试通过融化来重塑我的熊猫数据框

问题描述 投票:-2回答:1

enter image description here我正在尝试重塑如下所示的数据框:

enter image description here我想重塑我的数据框,使其看起来像这样:

python pandas melt
1个回答
0
投票

您可以结合使用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
© www.soinside.com 2019 - 2024. All rights reserved.