Marambo - 3 months ago 35

Python Question

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

tab1=tab.transpose()

pop=np.zeros((6,8),int)

pop[:,0:2]=tab1

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

pop[i,a]=np.random.choice(pop[:,(a-2)],1,replace=True)

# loope to complete the array "pop"

for r in range(2,8):

countage(r)

pop

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

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:

```
pop[i,a]=np.random.choice(toChooseFrom,1,replace=True)
```

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

```
pop[1:6,0]
```