Python “我怎么能?”;unpivot“;数据帧中的特定列?
我有一个熊猫数据框,例如:Python “我怎么能?”;unpivot“;数据帧中的特定列?,python,pandas,pivot-table,Python,Pandas,Pivot Table,我有一个熊猫数据框,例如: x = DataFrame.from_dict({'farm' : ['A','B','A','B'], 'fruit':['apple','apple','pear','pear'], '2014':[10,12,6,8], '2015':[11,13,7,9]}) 即: 如何将其转换为: farm fr
x = DataFrame.from_dict({'farm' : ['A','B','A','B'],
'fruit':['apple','apple','pear','pear'],
'2014':[10,12,6,8],
'2015':[11,13,7,9]})
即:
如何将其转换为:
farm fruit value year
0 A apple 10 2014
1 B apple 12 2014
2 A pear 6 2014
3 B pear 8 2014
4 A apple 11 2015
5 B apple 13 2015
6 A pear 7 2015
7 B pear 9 2015
我尝试了stack
和unstack
,但都没有成功
谢谢 这可以通过
pd.melt()
完成:
结果:
farm fruit year value
0 A apple 2014 10
1 B apple 2014 12
2 A pear 2014 6
3 B pear 2014 8
4 A apple 2015 11
5 B apple 2015 13
6 A pear 2015 7
7 B pear 2015 9
[8 rows x 4 columns]
我不确定这种操作的名称“melt”有多常见,但这就是R的
reformae2
软件包中的名称,它可能是这里的名字灵感来源。难以置信的简单和令人敬畏的名称-melt!非常感谢“融化”做得非常好。非常感谢。这正是我想要的。Melt是这个函数的一个很棒的名字
# value_name is 'value' by default, but setting it here to make it clear
pd.melt(x, id_vars=['farm', 'fruit'], var_name='year', value_name='value')
farm fruit year value
0 A apple 2014 10
1 B apple 2014 12
2 A pear 2014 6
3 B pear 2014 8
4 A apple 2015 11
5 B apple 2015 13
6 A pear 2015 7
7 B pear 2015 9
[8 rows x 4 columns]