2016-11-06 8 views
0

私は問題を抱えていました。行列の異なる行にランダムに2つの数値を選択したいと思います。そして、それらの数字を同じ行に置きますが、次の列でマトリックスを完成させます。例えば別の行でPythonのランダムな選択

#I create a matrix "pop" where there are numbers in the first and second column and where there are zeros on the other columns 
tab=np.array([[3, 2, 1, 0, 4, 6], [9, 8, 7, 8, 2, 0]]) 
tab1=tab.transpose() 
pop=np.zeros((6,8),int) 
pop[:,0:2]=tab1 

#I create a function "next" which complete the matrix "pop" by a 
#random sampling with replacement from the second previous column 
def next (a):#a is the column of the data 
    for i in range (0,6):#i is the row of the data 
     pop[i,a]=np.random.choice(pop[:,(a-2)],1,replace=True)# select a number by a random choice from second previous column 
     pop[i,a+1]=np.random.choice(pop[:,(a-1)],1,replace=True) 


# loope to complete the data "pop" 
for r in range(2,8): 
    if r % 2 ==0: 
     next(r) 

しかし、私の例では、マトリックスの同じ行に2つの数値を選択する確率が存在します。

def whynot (a):#a is the column of the data 
    for i in range (0,6):#i is the row of the data 
     number=np.random.choice(pop[:,(a-1):(a-2)],2,replace=False)# select a number by a random choice from second previous column 
     pop[i,a:a+1]=number 

をしかし、それは...動作しません:

は、だから私は試してみました!あなたの助けのために_(

感謝を

答えて

0

:-)最後に、私が見つかりました。長いことですが、よりよい解決策が存在すると思います。しかし、多分それが誰かを助けることができるので、私はスクリプトを掲載します。

def next (a):#a is the column of the data 
    for i in range (0,6):#i is the row of the data 
     number=np.arange(0,6,1) 
     c=np.random.choice(number,1,replace=False) 
     pop[i,a]=pop[c,a-2]# select a number by a random choice from second previous column 
     toChooseFrom1 = np.concatenate((pop[:c,(a-2)], pop[(c+1):,(a-2)])) 
     toChooseFrom2 = np.concatenate((pop[:c,(a-1)], pop[(c+1):,(a-1)])) 
     tochoose=np.concatenate([toChooseFrom1,toChooseFrom2]) 
     np.random.shuffle(tochoose) 
     pop[i,a+1]=np.random.choice(tochoose,1,replace=True) 


# loope to complete the data "pop" 
for r in range(2,8): 
    if r % 2 ==0: 
     next(r) 
関連する問題