如何从 Pandas DataFrame 中“反透视”特定列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23354124/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I "unpivot" specific columns from a pandas DataFrame?
提问by Racing Tadpole
I have a pandas DataFrame, eg:
我有一个Pandas数据帧,例如:
x = DataFrame.from_dict({'farm' : ['A','B','A','B'],
'fruit':['apple','apple','pear','pear'],
'2014':[10,12,6,8],
'2015':[11,13,7,9]})
ie:
IE:
2014 2015 farm fruit
0 10 11 A apple
1 12 13 B apple
2 6 7 A pear
3 8 9 B pear
How can I convert it to this: ?
我怎样才能把它转换成这个:?
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
I have tried stackand unstackbut haven't been able to make it work.
我已经尝试过stack,unstack但一直无法让它发挥作用。
Thanks!
谢谢!
回答by Marius
This can be done with pd.melt():
这可以通过以下方式完成pd.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')
Result:
结果:
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]
I'm not sure how common "melt" is as the name for this kind of operation, but that's what it's called in R's reshape2package, which probably inspired the name here.
我不确定“melt”作为这种操作的名称有多常见,但这就是它在 Rreshape2包中的名称,这可能启发了这里的名称。

