2017-06-03 3 views
1

私は(N、N)サイズで0しかない2D numpy配列を持っています。私は取得しています出力は1秒の完全なN、N配列である対角のものを除いた限られた数のランダムな場所でゼロ配列を塗りつぶす

import numpy as np 
def func(N=20): 
    x= np.zeros((N,N)) 
    for m in range(N): 
     for n in range(N): 
       if m == n: 
        x[m][n] == 0 
       else: 
        if np.count_nonzero(x) <= 12: 
          x.fill(1) 
          return (np.count_nonzero) 
    print (x) 

:私はランダムにされ、私が今まで試してみました何を0に等しい対角の位置の値を維持しながら、この配列に12 1Sを挿入したいです。彼らの数量が12に達した後に1を挿入することを止めることはできません。 どうすれば修正できますか?

答えて

1

あなたはnumpyのを使用していて、別のベクトル化ソリューションで大丈夫であれば、ここではマスキングと1だとnp.random.choiceでそれらの場所を選択するので -

def random_off_diag_fill(N, num_rand = 12, fillval=1): 
    # Initialize array 
    x= np.zeros((N,N),dtype=type(fillval)) 

    # Generate flat nondiagonal indices using masking 
    idx = np.flatnonzero(~np.eye(N,dtype=bool)) 

    # Select num_rand random indices from those and set those 
    # in a flattened view of the array to be as fillval 
    x.ravel()[np.random.choice(idx, num_rand, replace=0)] = fillval 
    return x 

サンプルの実行 -

In [57]: random_off_diag_fill(N=8, num_rand=12, fillval=1) 
Out[57]: 
array([[0, 0, 0, 0, 0, 1, 1, 0], 
     [0, 0, 0, 0, 0, 0, 0, 0], 
     [1, 0, 0, 0, 0, 0, 1, 1], 
     [0, 0, 0, 0, 0, 0, 0, 0], 
     [1, 1, 0, 0, 0, 1, 0, 0], 
     [0, 0, 1, 0, 1, 0, 0, 0], 
     [0, 0, 0, 0, 0, 0, 0, 0], 
     [1, 0, 1, 0, 0, 0, 0, 0]]) 

In [63]: random_off_diag_fill(N=5, num_rand=12, fillval=2.45) 
Out[63]: 
array([[ 0. , 0. , 0. , 0. , 2.45], 
     [ 2.45, 0. , 2.45, 0. , 2.45], 
     [ 0. , 2.45, 0. , 2.45, 2.45], 
     [ 2.45, 2.45, 0. , 0. , 0. ], 
     [ 2.45, 2.45, 0. , 2.45, 0. ]]) 
+0

ありがとうございます!まさに私が探していたものでした! – bapors

関連する問題