2017-07-02 9 views
1

私は同じ形状のN個のnumpy配列のリストを持っています。次の方法でそれらを1つの配列に結合する必要があります。出力配列の各要素は、入力配列の1つの対応する位置からランダムに取得する必要があります。N個の配列をnumpyでランダムに混合する方法は?

たとえば、[2,0,7]の位置で使用する値を決定する必要がある場合、すべての値をすべてのN個の入力配列のこの位置に配置します。だから、私はNの値を取得し、私はランダムに1つの値を選択します。

もう少し複雑にする。私は各入力配列に確率を割り当てることで、選択される値の確率が入力配列に依存するようにしたいと思います。

答えて

0
import numpy as np 
import itertools as it 

x = np.random.choice(np.arange(10), (2,3,4)) # pass probabilities with p=... 
N = 10 
a = [k*np.ones_like(x) for k in range(N)] # list of N arrays of same shape 
y = np.empty(a[0].shape) # output array 

# Generate list of all indices of arrays in a (no matter what shape, this is 
# handled with *) and set elements of output array y. 
for index in list(it.product(*list(np.arange(n) for n in x.shape))): 
    y[index] = a[x[index]][index] 
# a[x[index]] is the array chosen at a given index. 
# a[x[index]][index] is the element of this array at the given index. 

# expected result with the choice of list a: x==y is True for all elements 

「より複雑な部分は、」パラメータnumpy.random.choicepで処理されなければなりません。コメントには他のことを説明する必要があります。 *を使用すると、これはaの配列の任意の形状に対して機能するはずです(願っています)。

0

私たちは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.]]) 
関連する問題