mickeyt500 mickeyt500 - 2 months ago 18
Python Question

Writing a loop that chooses random values from columns - Python

Created a 2d array with (170,10) shape

i = np.array(range(1,1701)).reshape(170,10)


Want to write a loop that choses 5 random values without replacement from each column (or n number of columns) of i and output as below:

Group 1: [ 7 37 124 41 17]
Group 2: [302 261 257 323 234]
Group 3: [464 486 463 440 474]


So far i can pull random values from a single column:

print(np.random.choice(i[:,0],5 ,replace=False))


How do i put this in a for loop and pull for n number of columns with the displayed output (will use .function for that)

Answer Source

Let's use shape, arange, and random.choice:

for c in np.arange(i.shape[1]-1):
    print('Group {}: '.format(str(c+1)) + str(np.random.choice(i[:,c],5,replace=False)))

Output:

Group 1: [1521  231  671  801  711]
Group 2: [ 612  192 1172 1242 1322]
Group 3: [ 543  213 1453  723  973]
Group 4: [ 404 1334  474  294 1044]
Group 5: [1615 1455 1025 1665 1395]
Group 6: [1116 1336 1086 1626  536]
Group 7: [367 347 887 297 237]
Group 8: [1088 1188 1288   58  608]
Group 9: [1439 1289  869  349 1589]