从2D numpy数组快速计算随机3D numpy数组

nic*_*sts 6 python arrays numpy

我有一个二维的整数数组,我们称之为"A".

我想创建一个所有1和0的三维数组"B",这样:

  • 对于任何固定的(i,j)sum(B[i,j,:])==A[i.j],即B[i,j,:]包含A[i,j] 1s在其中
  • 1s随机放置在第3维.

我知道如何使用标准的python索引来做到这一点,但结果却很慢.

我正在寻找一种方法来利用可以使Numpy快速的功能.

这是我如何使用标准索引来做到这一点:

B=np.zeros((X,Y,Z))
indexoptions=range(Z)

for i in xrange(Y):
    for j in xrange(X):
        replacedindices=np.random.choice(indexoptions,size=A[i,j],replace=False)
        B[i,j,[replacedindices]]=1
Run Code Online (Sandbox Code Playgroud)

有人可以解释我怎么能以更快的方式做到这一点?

编辑:这是一个例子"A":

A=np.array([[0,1,2,3,4],[0,1,2,3,4],[0,1,2,3,4],[0,1,2,3,4],[0,1,2,3,4]])
Run Code Online (Sandbox Code Playgroud)

在这种情况下,X = Y = 5且Z> = 5

War*_*ser 4

本质上与 @JohnZwinck 和 @DSM 相同,但具有shuffle用于洗牌给定轴的函数:

import numpy as np

def shuffle(a, axis=-1):
    """
    Shuffle `a` in-place along the given axis.

    Apply numpy.random.shuffle to the given axis of `a`.
    Each one-dimensional slice is shuffled independently.
    """
    b = a.swapaxes(axis,-1)
    # Shuffle `b` in-place along the last axis.  `b` is a view of `a`,
    # so `a` is shuffled in place, too.
    shp = b.shape[:-1]
    for ndx in np.ndindex(shp):
        np.random.shuffle(b[ndx])
    return


def random_bits(a, n):
    b = (a[..., np.newaxis] > np.arange(n)).astype(int)
    shuffle(b)
    return b


if __name__ == "__main__":
    np.random.seed(12345)

    A = np.random.randint(0, 5, size=(3,4))
    Z = 6

    B = random_bits(A, Z)

    print "A:"
    print A
    print "B:"
    print B
Run Code Online (Sandbox Code Playgroud)

输出:

A:
[[2 1 4 1]
 [2 1 1 3]
 [1 3 0 2]]
B:
[[[1 0 0 0 0 1]
  [0 1 0 0 0 0]
  [0 1 1 1 1 0]
  [0 0 0 1 0 0]]

 [[0 1 0 1 0 0]
  [0 0 0 1 0 0]
  [0 0 1 0 0 0]
  [1 0 1 0 1 0]]

 [[0 0 0 0 0 1]
  [0 0 1 1 1 0]
  [0 0 0 0 0 0]
  [0 0 1 0 1 0]]]
Run Code Online (Sandbox Code Playgroud)