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

2 Answers 2

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]


Sign up to request clarification or add additional context in comments.

2 Comments

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!
I have updated the code, have a look at it. Just ask for example if the index is not in the result.
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]

4 Comments

Thanks! just one more thing, is there a way to have each index only taken once?
@AdryanZiegler Yes, I edited the code for that.
This worked perfectly! thanks a lot! i tweaked it a little bit and removed the "item" from the whole code, and made it: if indexNum not in chosenIndicies: append
@AdryanZiegler That's great. Glad to help you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.