Home > Mobile >  How do I modify the output of a loop that selects 2 number from each column of a numpy array
How do I modify the output of a loop that selects 2 number from each column of a numpy array

Time:07-03

code:

import numpy as np

m =np.array([[7, 0, 0, 6],

 [5, 6, 6, 1],

 [4, 1, 6, 7],

 [5, 3, 4, 7]])

np.random.seed(55)

for i in m:

    print(np.random.choice(i, 2, replace = False))

output :

[7 6]

[1 6]

[4 6]

[4 5]

How do I modify the code so that I get the below output?

Group 1: [7 6]

Group 2: [1 6]

Group 3: [4 6]

Group 4: [4 5]

CodePudding user response:

This should work:


import numpy as np

m =np.array([[7, 0, 0, 6],

[5, 6, 6, 1],

[4, 1, 6, 7],

[5, 3, 4, 7]])

np.random.seed(55)

for i in range(len(m)):    
    print("Group",i,":",np.random.choice(m[i], 2, replace = False))

CodePudding user response:

Something like:

for n, i in enumerate(m, 1):
    print(f"Group {n}: {np.random.choice(i, 2, replace = False)}")

enumerate(x) gives us an automatic counter when we iterate over x. By default it starts at 0, but here we make it start at 1, to match your example output.

  • Related