python - numpy array to permutation matrix -
np.array([1,2,3])
i've got numpy array. turn numpy array tuples of each 1:1 permutation. 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 efficiently? need operation few million times.
if you're working numpy, don't work tuples. use power , add dimension of size two. recommendation is:
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 general array:
ix = np.vstack([x _ in range(x.shape[0])]) return np.vstack(([ix], [ix.t])).t
this produce want:
array([[[1, 1], [1, 2], [1, 3]], [[2, 1], [2, 2], [2, 3]], [[3, 1], [3, 2], [3, 3]]])
but 3d matrix, can see when looking @ shape:
out[25]: (3l, 3l, 2l)
this more efficient solution permutations array size get's bigger. timing solution against @kasra's yields 1ms mine vs. 46ms 1 permutations array of size 100. @ashwinichaudhary's solution more efficient though.
Comments
Post a Comment