1

I'm creating a numpy zero array of 10x5 and i wish to fill in each column with a shuffled list of numbers from 1-10. However I have a problem because it only fills in the first column and the list.pop() doesn't work plus i think my nested for loops even though i tried using the row and preferences in different order. Any help would be greatly appreciated.

i = 0
j = 0

for column in matrix:

    preferences = [1,2,3,4,5,6,7,8,9,10]

    random.shuffle(preferences)

    for number in preferences:

        for row in matrix:
            chosen = preferences.pop(0)
            matrix[j,i] = chosen
        j+= 1

i+= 1

2 Answers 2

6

Since you used pop in your example, I thought you may not want repeat within each column. numpy.random.shuffle shuffles elements in place.

>>> M = N.repeat(N.arange(1,11), 5).reshape(10,-1)
>>> M
array([[ 1,  1,  1,  1,  1],
       [ 2,  2,  2,  2,  2],
       [ 3,  3,  3,  3,  3],
       [ 4,  4,  4,  4,  4],
       [ 5,  5,  5,  5,  5],
       [ 6,  6,  6,  6,  6],
       [ 7,  7,  7,  7,  7],
       [ 8,  8,  8,  8,  8],
       [ 9,  9,  9,  9,  9],
       [10, 10, 10, 10, 10]])
>>> for i in range(5): 
...    N.random.shuffle(M[:,i])
>>> M
array([[ 3,  9,  7,  9,  2],
       [ 5,  4,  2,  5,  3],
       [ 8,  8,  8,  1,  4],
       [ 1,  2,  6, 10,  8],
       [ 2,  1,  9,  2,  5],
       [ 7,  7, 10,  7,  1],
       [ 4,  3,  5,  8,  9],
       [ 6,  5,  4,  4,  7],
       [10, 10,  3,  6,  6],
       [ 9,  6,  1,  3, 10]])
>>>
Sign up to request clarification or add additional context in comments.

2 Comments

the reason i used the for loops to insert because the position of the 1 and 10 are important to me (1 means most favourite and 10 being least). Your way would mean that i would create and fill then go through and find.
doug's method have 1/10 chance of picking one of 10 values regardless of what other values are chosen. Like, the last column of his has two 7s and three 5s. My method fixed that one column has one and only one each of 10 values. Pick the one you need.
1
>>> import numpy as NP

>>> fnx = lambda v : NP.random.randint(1, 11, v)
>>> A = NP.zeros(5, 10)
>>> for c in range(A.shape[0]):
        A[c,:] = fnx(10)
>>> A = A.T
>>> A
  array([[  5.,   1.,   3.,   8.,   5.],
         [  4.,  10.,   4.,   3.,  10.],
         [  6.,   6.,   3.,   2.,   7.],
         [  4.,   4.,  10.,   5.,   4.],
         [  8.,   6.,   6.,   2.,  10.],
         [ 10.,   9.,  10.,   6.,  10.],
         [  7.,   4.,   2.,   2.,   7.],
         [  9.,   2.,   9.,   4.,   7.],
         [ 10.,   5.,   3.,   5.,   7.],
         [  3.,   9.,   3.,   3.,   1.]])

1 Comment

i want a shuffled list from one to 10 in every column.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.