2016-11-06 14 views
0

我遇到了一個問題,我想在矩陣的不同行上隨機選擇兩個數字。之後,將這些數字放在同一行上,但在下面的列上填寫矩陣。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) 

但在我的例子中,存在一個概率在同一行的矩陣中選擇兩個號碼。

所以,我想:

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)