2014-03-02 35 views
28

我无法弄清楚如何在python中使用熊猫做“反向熔化”。 这是我的出发数据在python熊猫中熔化的对面

import pandas as pd 

from StringIO import StringIO 

origin = pd.read_table(StringIO('''label type value 
x a 1 
x b 2 
x c 3 
y a 4 
y b 5 
y c 6 
z a 7 
z b 8 
z c 9''')) 

origin 
Out[5]: 
    label type value 
0  x a  1 
1  x b  2 
2  x c  3 
3  y a  4 
4  y b  5 
5  y c  6 
6  z a  7 
7  z b  8 
8  z c  9 

这是我想什么有:

label a b c 
     x 1 2 3 
     y 4 5 6 
     z 7 8 9 

我敢肯定有一个简单的方法来做到这一点,但我不知道怎么办。

+3

[熔体的文档字符串](http://pandas.pydata.org/ pandas-docs/stable/generated/pandas.melt.html):“Unpivots”一个DataFrame ... :) –

+0

StringIO has mov在python3中编辑为'io'。使用'从io import StringIO' python3。 – Daniel

+1

我在这个[** Q&A **](https://stackoverflow.com/q/47152691/2336654)中提供了几个详细的示例和替代方法, – piRSquared

回答

41

有几种方法;使用.pivot

>>> origin.pivot(index='label', columns='type')['value'] 
type a b c 
label   
x  1 2 3 
y  4 5 6 
z  7 8 9 

[3 rows x 3 columns] 

使用pivot_table

>>> origin.pivot_table(values='value', index='label', columns='type') 
     value  
type  a b c 
label    
x   1 2 3 
y   4 5 6 
z   7 8 9 

[3 rows x 3 columns] 

.groupby随后.unstack

>>> origin.groupby(['label', 'type'])['value'].aggregate('mean').unstack() 
type a b c 
label   
x  1 2 3 
y  4 5 6 
z  7 8 9 

[3 rows x 3 columns]