如何从pandas DataFrame中"取消"特定列?

Rac*_*ole 23 python pivot-table pandas

我有一个pandas DataFrame,例如:

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

即:

   2014  2015 farm  fruit
0    10    11    A  apple
1    12    13    B  apple
2     6     7    A   pear
3     8     9    B   pear
Run Code Online (Sandbox Code Playgroud)

我怎样才能将其转换为:

  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
Run Code Online (Sandbox Code Playgroud)

我尝试过stack,unstack但一直没能使它发挥作用.

谢谢!

Mar*_*ius 25

这可以通过以下方式完成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')
Run Code Online (Sandbox Code Playgroud)

结果:

  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]
Run Code Online (Sandbox Code Playgroud)

我不确定这种操作的名称是多么常见的"融化",但这就是它在R的reshape2包中所称的,这可能激发了这里的名字.