2016-08-02 11 views
4

{(k,i): value, ...}というラベルの付いた辞書があります。この辞書を、配列[k,i]の配列の要素に与えられた値が、ラベル(k,i)の辞書の値である2次元配列に変換する必要があります。行の長さは必ずしも同じサイズである必要はありません(たとえば、行k = 4i = 60に、行k = 24はインデックスi = 31になる可能性があります)。アシンメトリのために、特定の行のすべての追加エントリを0にして、長方形の行列を持たせても問題ありません。既知のインデックスを持つ辞書を多次元配列に変換する

# Get keys (as indices for output) and values as arrays 
idx = np.array(d.keys()) 
vals = np.array(d.values()) 

# Get dimensions of output array based on max extents of indices 
dims = idx.max(0)+1 

# Setup output array and assign values into it indexed by those indices 
out = np.zeros(dims,dtype=vals.dtype) 
out[idx[:,0],idx[:,1]] = vals 

我々はまた、最終的な出力を得るためにスパース行列を使用することができます -

+0

サンプル入力/出力? –

答えて

3

は、ここでのアプローチです。例えばcoordinate format sparse matrices。これは、疎な行列として保存すると効率的なメモリになります。私たちが使用できる任意の次元数のndarraysため、それが一般的なようにするには

In [70]: d 
Out[70]: {(1, 4): 120, (2, 2): 72, (2, 3): 100, (5, 2): 88} 

In [71]: out 
Out[71]: 
array([[ 0, 0, 0, 0, 0], 
     [ 0, 0, 0, 0, 120], 
     [ 0, 0, 72, 100, 0], 
     [ 0, 0, 0, 0, 0], 
     [ 0, 0, 0, 0, 0], 
     [ 0, 0, 88, 0, 0]]) 

の直鎖 -

from scipy.sparse import coo_matrix 

out = coo_matrix((vals, (idx[:,0], idx[:,1])), dims).toarray() 

サンプル実行 - だから、最後のステップは次のようなもので置き換えることができます出力配列に値を代入するにはnp.putを使用します。このように、私たちの最初のアプローチでは、ちょうどこのような何かを使用して値を代入する最後のステップを置き換える -

np.put(out,np.ravel_multi_index(idx.T,dims),vals) 

サンプル実行 -

In [106]: d 
Out[106]: {(1,0,0): 99, (1,0,4): 120, (2,0,2): 72, (2,1,3): 100, (3,0,2): 88} 

In [107]: out 
Out[107]: 
array([[[ 0, 0, 0, 0, 0], 
     [ 0, 0, 0, 0, 0]], 

     [[ 99, 0, 0, 0, 120], 
     [ 0, 0, 0, 0, 0]], 

     [[ 0, 0, 72, 0, 0], 
     [ 0, 0, 0, 100, 0]], 

     [[ 0, 0, 88, 0, 0], 
     [ 0, 0, 0, 0, 0]]]) 
0

することができ辞書・オブ・キーまばらな形式がありますこのような辞書から構築されています。 Divakar'sdサンプルを皮切り

In [1190]: M=sparse.dok_matrix((6,5),dtype=int) 
In [1191]: M 
Out[1191]: 
<6x5 sparse matrix of type '<class 'numpy.int32'>' 
    with 0 stored elements in Dictionary Of Keys format> 

辞書update経由d値を追加します。

In [1189]: d={(1, 4): 120, (2, 2): 72, (2, 3): 100, (5, 2): 88} 

は右形状とDTYPEの空のスパース行列を作ります。これは、この特定の疎フォーマットがdictサブクラスであるために機能します。けれどもウェアなり、このトリックは(少なくともない私の知ること)に文書化されていないこと:

In [1192]: M.update(d) 
In [1193]: M 
Out[1193]: 
<6x5 sparse matrix of type '<class 'numpy.int32'>' 
    with 4 stored elements in Dictionary Of Keys format> 
In [1194]: M.A # convert M to numpy array (handy display trick) 
Out[1194]: 
array([[ 0, 0, 0, 0, 0], 
     [ 0, 0, 0, 0, 120], 
     [ 0, 0, 72, 100, 0], 
     [ 0, 0, 0, 0, 0], 
     [ 0, 0, 0, 0, 0], 
     [ 0, 0, 88, 0, 0]]) 

Mcsrcoo、他のまばらな形式に変換することができます。実際にはsparseは、用途(表示、計算など)に応じて、この種の変換を単独で行います。

In [1196]: print(M) 
    (2, 3) 100 
    (5, 2) 88 
    (1, 4) 120 
    (2, 2) 72