0

If I have:

x = np.array(([1,4], [2,5], [2,6], [3,4], [3,6], [3,7], [4,3], [4,5], [5,2]))

for item in range(3):
    choice = random.choice(x)

How can I get the index number of the random choice taken from the array?

I tried:

indexNum = np.where(x == choice)
print(indexNum[0])

But it didn't work.

I want the output, for example, to be something like:

chosenIndices = [1 5 8]
john-hen
  • 4,410
  • 2
  • 23
  • 40
  • Does this answer your question? [Find the row indexes of several values in a numpy array](https://stackoverflow.com/questions/38674027/find-the-row-indexes-of-several-values-in-a-numpy-array) – DrBwts May 11 '21 at 20:23

2 Answers2

3

Another possibility is using np.where and np.intersect1d. Here random choice without repetition.

x = np.array(([1,4], [2,5], [2,6], [3,4], [3,6], [3,7], [4,3], [4,5], [5,2]))

res=[]
cont = 0

while cont<3:
    choice = random.choice(x)
    ind = np.intersect1d(np.where(choice[0]==x[:,0]),np.where(choice[1]==x[:,1]))[0]
    if ind not in res:
        res.append(ind)
        cont+=1

print (res)

# Output [8, 1, 5]


Veronica
  • 41
  • 4
  • 1
    Thats just perfect! thanks you so much! Just one more thing, is there a way to have each index only taken once? so i dont get same index more than once? Thanks! – Adryan Ziegler May 11 '21 at 21:04
  • 1
    I have updated the code, have a look at it. Just ask for example if the index is not in the result. – Veronica May 11 '21 at 21:28
1

You can achieve this by converting the numpy array to list of tuples and then apply the index function.

This would work:

import random
import numpy as np
chosenIndices = []
x = np.array(([1,4], [2,5], [2,6], [3,4], [3,6], [3,7], [4,3], [4,5], [5,2]))
x = x.T
x = list(zip(x[0],x[1]))
item = 0
while len(chosenIndices)!=3:
    choice = random.choice(x)
    indexNum = x.index(choice)
    if indexNum in chosenIndices: # if index already exist, then it will rerun that particular iteration again.
        item-=1
    else:
        chosenIndices.append(indexNum)
print(chosenIndices) # Thus all different results.

Output:

[1, 3, 2]
KnowledgeGainer
  • 1,017
  • 1
  • 5
  • 14