numpy的阵列排列矩阵

numpy的阵列排列矩阵

本文介绍了numpy的阵列排列矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我有numpy的数组。我希望把它变成每1元组numpy的阵列:1置换。像这样的:

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

就如何有效地做到这一点有什么想法?我需要做此操作了几百万次。

解决方案

如果您正在使用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

而对于一般的数组:

 九= np.vstack([X为_范围内(x.shape [0])])
返回np.vstack(([九],[ix.T)):T

这会产生你想要什么:

 阵列([[[1,1]
        [1,2],
        [1,3]]       [[2,1],
        [2,2],
        [2,3]]       [[3,1]
        [3,2],
        [3,3]]])

但作为一个三维矩阵,如在看它的形状,当你可以看到:

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

这是比排列为数组大小获取的更大的解决方案更有效。时序我反对@ Kasra的产量1ms的解决方案,矿山与46ms为一个与排列尺寸为100的数组@ AshwiniChaudhary的解决方案是更有效的,但。

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

I've got 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 a few million times.

解决方案

If you're working with numpy, don't work with tuples. Use its power and add another dimension of size two.My 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 for a general array:

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

This will produce 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 3D matrix, as you can see when looking at its shape:

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

This is more efficient than the solution with permutations as the array size get's bigger. Timing my solution against @Kasra's yields 1ms for mine vs. 46ms for the one with permutations for an array of size 100. @AshwiniChaudhary's solution is more efficient though.

这篇关于numpy的阵列排列矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 12:40