我有一个熊猫DataFrame,我想重塑它。
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
发布于 2019-03-15 04:10:32
使用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
https://stackoverflow.com/questions/55171153
复制相似问题