2017-08-12 6 views
1

私は3列のvaluerow_indexcolumn_indexのパンダデータフレームを持っています。私は、関連する行と列、および未知の要素に配置されたデータフレームの値が0である行列を作成したいと考えています。データフレーム列の値を2次元行列にするにはどうすればよいですか?

私が作った、このようなサイクル用:

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

てみ '配列= 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

私はあなたがfillnapivotが必要だと思うし、列と行の欠損値のため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]] 
関連する問題