2014-12-05 93 views
3
np.array([1,2,3]) 

我有numpy數組。我想把它變成一個numpy數組,每個1:1排列的元組。像這樣:numpy數組到排列矩陣

np.array([ 
    [(1,1),(1,2),(1,3)], 
    [(2,1),(2,2),(2,3)], 
    [(3,1),(3,2),(3,3)], 
]) 

有關如何有效地做到這一點的任何想法?我需要做這個操作幾百萬次。

回答

4

如果你使用numpy,不要使用元組。使用它的力量並添加另一個尺寸爲2的尺寸。 我的建議是:

x = np.array([1,2,3]) 
np.vstack(([np.vstack((x, x, x))], [np.vstack((x, x, x)).T])).T 

或:

im = np.vstack((x, x, x)) 
np.vstack(([im], [im.T])).T 

而對於一般的數組:

ix = np.vstack([x for _ in range(x.shape[0])]) 
return np.vstack(([ix], [ix.T])).T 

這將產生你想要什麼:

array([[[1, 1], 
     [1, 2], 
     [1, 3]], 

     [[2, 1], 
     [2, 2], 
     [2, 3]], 

     [[3, 1], 
     [3, 2], 
     [3, 3]]]) 

但作爲3D矩陣,

Out[25]: (3L, 3L, 2L) 

這比排列爲數組大小獲取的更大的解決方案更有效:你可以看它的形狀,當看到。針對@ Kasra的解決方案,我的解決方案的收益率爲1ms,而對於大小爲100的排列的解決方案,收益率爲46ms。@ AshwiniChaudhary的解決方案雖然效率更高。

1

您可以使用itertools.product來獲取排列,然後將結果轉換爲numpy數組。

>>> from itertools import product 
>>> p=list(product(a,repeat=2)) 
>>> np.array([p[i:i+3] for i in range(0,len(p),3)]) 
array([[[1, 1], 
     [1, 2], 
     [1, 3]], 

     [[2, 1], 
     [2, 2], 
     [2, 3]], 

     [[3, 1], 
     [3, 2], 
     [3, 3]]]) 
5

你可以做這樣的事情:

>>> a = np.array([1, 2, 3]) 
>>> n = a.size     
>>> perm = np.empty((n, n, 2), dtype=a.dtype) 
perm[..., 0] = a[:, None] 
perm[..., 1] = a 
... 
>>> perm 
array([[[1, 1], 
     [1, 2], 
     [1, 3]], 

     [[2, 1], 
     [2, 2], 
     [2, 3]], 

     [[3, 1], 
     [3, 2], 
     [3, 3]]]) 

時機比較:

>>> a = np.array([1, 2, 3]) 
>>> n = a.size 
>>> np.vstack((np.repeat(a, n), np.tile(a, n))).T.reshape(n, n, 2) 
array([[[1, 1], 
     [1, 2], 
     [1, 3]], 

     [[2, 1], 
     [2, 2], 
     [2, 3]], 

     [[3, 1], 
     [3, 2], 
     [3, 3]]]) 

或者像suggested by @Jaime,如果我們充分利用廣播在這裏你可以避開10倍加速

>>> a = np.array([1, 2, 3]*100) 
>>> %%timeit     
np.vstack((np.repeat(a, n), np.tile(a, n))).T.reshape(n, n, 2) 
... 
1000 loops, best of 3: 934 µs per loop 
>>> %%timeit     
perm = np.empty((n, n, 2), dtype=a.dtype)      
perm[..., 0] = a[:, None] 
perm[..., 1] = a 
... 
10000 loops, best of 3: 111 µs per loop 
+2

如果遠離平鋪並重復使用廣播:'perm = np.empty((n,n,2),dtype = a),您可以獲得大幅提速(對於100項數組,10x)。 D型); perm [...,0] = a;燙髮[...,1] = a [:.無]' – Jaime 2014-12-05 21:26:18