我该如何“取消透视"?从 pandas DataFrame的特定列? [英] How can I "unpivot" specific columns from a pandas DataFrame?

查看:61
本文介绍了我该如何“取消透视"?从 pandas DataFrame的特定列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个熊猫DataFrame,例如:

I have a pandas DataFrame, eg:

x = DataFrame.from_dict({'farm' : ['A','B','A','B'], 
                         'fruit':['apple','apple','pear','pear'], 
                         '2014':[10,12,6,8], 
                         '2015':[11,13,7,9]})

即:

   2014  2015 farm  fruit
0    10    11    A  apple
1    12    13    B  apple
2     6     7    A   pear
3     8     9    B   pear

如何将其转换为:?

  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

我尝试过stackunstack,但无法使其正常工作.

I have tried stack and unstack but haven't been able to make it work.

谢谢!

推荐答案

这可以通过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')

结果:

  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]

我不确定融解"作为这种操作的名称有多常见,但这就是R的reshape2程序包中所称的名称,这可能启发了此名称.

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 reshape2 package, which probably inspired the name here.

这篇关于我该如何“取消透视"?从 pandas DataFrame的特定列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆