我有一个 pandas DataFrame,我想 reshape 它。
Country 1991 1992 1993
Deutschland 1 2 3
Griechenland 4 7 0
如何创建一个如下所示的新 DataFrame:
Country Year Value
Deutschland 1991 1
Deutschland 1992 2
Deutschland 1993 3
Griechenland 1991 4
Griechenland 1992 7
Griechenland 1993 0
最佳答案
使用melt
(然后按国家和年份对值进行排序并重置索引):
(df.melt('Country', var_name='Year', value_name='Value')
.sort_values(['Country', 'Year'])
.reset_index(drop=True))
输出:
Country Year Value
0 Deutschland 1991 1
1 Deutschland 1992 2
2 Deutschland 1993 3
3 Griechenland 1991 4
4 Griechenland 1992 7
5 Griechenland 1993 0
关于python - pd DataFrame 中列的列名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55171153/