2017-08-12 58 views
1

我有熊猫数据帧3列value,row_index,column_index。我想创建一个矩阵,其中放置在相关行和列以及未知元素的数据帧的值为零。如何在2d矩阵中放置值od数据帧列?

我已经做了的周期是这样的:

N_rows = df.row_index.max() 
N_cols = df.column_index.max() 
A = np.zeros((N_rows, N_cols)) 
for i in df.row_index: 
    for j in df.column_index: 
     np.put(A, i*N_cols+j, df['value'][(df.row_index==i) & 
              (df.column_index==j)]) 

,但它的工作原理很慢。

我该如何做得更快?

+0

尝试'array = df.fillna(0).values' –

回答

0

只需修改@ jezrael解决方案中的小部分即可。你实际上可以使用熊猫as_matrix()函数来获得阵列:

df = pd.DataFrame({'value':[2,4,5], 
        'row_index':[2,3,4], 
        'col_index':[0,2,3]}) 

df.pivot('row_index', 'col_index', 'value').fillna(0).as_matrix() 
# array([[ 2., 0., 0.], 
#  [ 0., 4., 0.], 
#  [ 0., 0., 5.]]) 
1

我认为你需要pivotfillna和失踪列的值和行添加reindex,持续numpy的阵列添加values

df = pd.DataFrame({'value':[2,4,5], 
        'row_index':[2,3,4], 
        'col_index':[0,2,3]}) 

print (df) 
    col_index row_index value 
0   0   2  2 
1   2   3  4 
2   3   4  5 

rows = np.arange(df.row_index.max()+1) 
cols = np.arange(df.col_index.max()+1) 

print (df.pivot('row_index', 'col_index', 'value') 
     .fillna(0) 
     .reindex(index=rows, columns=cols, fill_value=0)) 
col_index 0 1 2 3 
row_index      
0   0.0 0.0 0.0 0.0 
1   0.0 0.0 0.0 0.0 
2   2.0 0.0 0.0 0.0 
3   0.0 0.0 4.0 0.0 
4   0.0 0.0 0.0 5.0 

a = df.pivot('row_index', 'col_index', 'value') 
     .fillna(0) 
     .reindex(index=rows, columns=cols, fill_value=0) 
     .values 
print (a) 
[[ 0. 0. 0. 0.] 
[ 0. 0. 0. 0.] 
[ 2. 0. 0. 0.] 
[ 0. 0. 4. 0.] 
[ 0. 0. 0. 5.]] 

另一种解决方案与set_indexunstack

print (df.set_index(['row_index', 'col_index'])['value'] 
     .unstack(fill_value=0) 
     .reindex(index=rows, columns=cols, fill_value=0)) 

col_index 0 1 2 3 
row_index    
0   0 0 0 0 
1   0 0 0 0 
2   2 0 0 0 
3   0 0 4 0 
4   0 0 0 5 


a = df.set_index(['row_index', 'col_index'])['value'] 
     .unstack(fill_value=0) 
     .reindex(index=rows, columns=cols, fill_value=0) 
     .values 
print (a) 
[[0 0 0 0] 
[0 0 0 0] 
[2 0 0 0] 
[0 0 4 0] 
[0 0 0 5]]