2014-03-04 47 views
8

我有以下代码,它取得熊猫数据框的一列中的值,并使它们成为新数据框的列。数据帧第一列中的值将成为新数据帧的索引。将列值更改为大熊猫中的列标题

从某种意义上说,我想把一个邻接表变成一个邻接矩阵。这里是到目前为止的代码:

import pandas as pa 
print "Original Data Frame" 
# Create a dataframe 
oldcols = {'col1':['a','a','b','b'], 'col2':['c','d','c','d'], 'col3':[1,2,3,4]} 
a = pa.DataFrame(oldcols) 
print a 

# The columns of the new data frame will be the values in col2 of the original 
newcols = list(set(oldcols['col2'])) 
rows = list(set(oldcols['col1'])) 

# Create the new data matrix 
data = np.zeros((len(rows), len(newcols))) 

# Iterate over each row and fill in the new matrix 
for row in zip(a['col1'], a['col2'], a['col3']): 
    rowindex = rows.index(row[0]) 
    colindex = newcols.index(row[1]) 
    data[rowindex][colindex] = row[2] 

newf = pa.DataFrame(data) 
newf.columns = newcols 
newf.index = rows 

print "New data frame" 
print newf 

这适用于这个特定实例:

Original Data Frame 
    col1 col2 col3 
0 a c  1 
1 a d  2 
2 b c  3 
3 b d  4 
New data frame 
    c d 
a 1 2 
b 3 4 

如果COL3的值不是数字就会失败。我的问题是,是否有一个更优雅/强大的方式来做到这一点?

回答

11

这看起来像a job for pivot

import pandas as pd 
oldcols = {'col1':['a','a','b','b'], 'col2':['c','d','c','d'], 'col3':[1,2,3,4]} 
a = pd.DataFrame(oldcols) 

newf = a.pivot(index='col1', columns='col2') 
print(newf) 

产量

 col3 
col2  c d 
col1   
a  1 2 
b  3 4 

如果你不想多指标列,您可以使用删除col3

newf.columns = newf.columns.droplevel(0) 

这将然后收益率

col2 c d 
col1  
a  1 2 
b  3 4 
+0

哇,*几乎*让我后悔编写代码做'手动': - P –

+2

不要担心 - 它让你更加欣赏熊猫! – unutbu