Numpy array to permutation matrix

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

I have a numpy array. I would like to turn it into a numpy array with tuples of each 1: 1 permutation. Like this:

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

Any thoughts on how to do this efficiently? I need to do this operation several million times.

+3
source share
3 answers

If you work with numpy, do not work with tuples. Use his power and add another dimension of size two. My recommendation:

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

or

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

And for the general array:

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

This will result in what you want:

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

But as a three-dimensional matrix, as you can see, looking at its shape:

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

This is more efficient than a permutation solution as the size of the array becomes larger. The timing of my decision against @Kasra is 1 ms for mine versus 46 ms for one with permutations for an array of size 100. The @AshwiniChaudhary solution is more efficient.

+4
source

You can do something like this:

 >>> 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]]]) 

Or as suggested by @Jaime , you can get 10x acceleration if you use the translation here:

 >>> 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]]]) 

Time comparison:

 >>> 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 
+5
source

You can use itertools.product to get permutations and then convert the result to a numpy array.

 >>> 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]]]) 
+1
source

Source: https://habr.com/ru/post/1013263/


All Articles