私たちはnumpy組み込み関数を使ってこれを扱います:forループより高速です。
import numpy as np
# N = 3 dummy arrays for the example
a = np.zeros([4, 5])
b = 10 * np.ones([4, 5])
c = 2 * b
arr = np.array([a, b, c]) # this is a 3D array containing your N arrays
N = arr.shape[0]
idx = np.random.choice(range(N), 4 * 5) # 4 and 5 are the common dimensions of your N arrays
# treating this a a 1D problem, but treating as 2D is possible too.
arr.reshape(N, 20)[idx.ravel(), np.arange(20)].reshape(4, 5)
あなたが異なる確率を持っているしたい場合は、(1に合計しなければならない形状の配列(Nを、))np.random.choiceするパラメータpを渡すことができます。
idx_p = np.random.choice(range(n_arr), 4 * 5, p = [0.1, 0.2, 0.7])
arr.reshape(n_arr, 20)[idx_p.ravel(), np.arange(20)].reshape(4, 5)
これは次のようになります。
# first result:
array([[ 0., 0., 0., 20., 10.],
[ 20., 0., 20., 0., 10.],
[ 0., 10., 0., 10., 0.],
[ 10., 20., 10., 0., 10.]])
# second result with many 20, a few 10 and fewer 0:
array([[ 10., 0., 20., 20., 20.],
[ 20., 0., 20., 20., 20.],
[ 10., 20., 20., 20., 10.],
[ 20., 10., 20., 20., 20.]])