dimanche 6 novembre 2016

python random choice on different rows

I've a problem, I would like randomly select two number on different rows of a matrix. And after, put those numbers on the same row but on the following columns for complete the matrix.

For example:

#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)

But in my example, there exist a probability to choose two numbers on the same row of the matrix.

So I tried:

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

But it doesn't work... :_(

Thanks for your help!

:-)




Aucun commentaire:

Enregistrer un commentaire