Marambo Marambo - 1 year ago 101
Python Question

Python: random choice on matrix without selecting the number on the same line

I have a problem because I would like realise a matrix by a random selection with replacement from the previous column without selecting the number that is on the same line as this element.

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

#I create a function "cuntage" which complete the matrix "pop" by a
#random sampling with replacement from the second previous column
def countage (a):
for i in range (0,6):

# loope to complete the array "pop"
for r in range(2,8):


But the problem is that I would like select, by a random choice from second previous column, each element of the matrix but without selecting the number that is on the same line as this element.

For example, in the matrix pop, the element pop[0,2] is select in pop[1:6,0].

Thanks for your responses!!


Answer Source

You could just glue the array you want together out of its parts

toChooseFrom = np.concatenate((pop[:i,(a-2)], pop[(i+1):,(a-2)]))

and then use np.random.choice just like you did:


In the example you gave above, the element pop[0,2] would choose from the concatenation of the two arrays

pop[:i,(a-2)] == pop[:0,0] == []
pop[(i+1):,(a-2)] == pop[1:6,0]

which is just

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download