-1

I want to find the index/location of a randomly chosen number in a 1D NumPy array within the array itself, but when I try the following:

a = np.array(np.linspace(1,10,10))
b = np.random.choice(a)
print(a.index(b))

It doesn't work and can't figure out where the problem is. Does anyone have an idea?

Thanks in advance!

EDIT: how do you only index the randomly chosen value if the values in the NumPy array are identical, for example:

a = np.array(np.linspace(10,10,10))
1

3 Answers 3

1

You have to use where function as already answer here Is there a NumPy function to return the first index of something in an array?

import numpy as np
a = np.array(np.linspace(1,10,10))
b = np.random.choice(a)
print(np.where(a==b))

If the value are the same, where return multiple index, example:

a = np.array(np.linspace(10,10,10))
print(np.where(a==10))

>>> (array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),)

Here all index are turned because 10 is in all position.

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

5 Comments

It worked! Thanks! Another question if i'm not bothering you: what if the values in the array are identical? Because then this method doesn't work properly unfortunately.
I see. Thanks! But is it possible to only index the randomly chosen value in the NumPy array containing identical values? (again, sorry for bothering you)
I don't understand what you're trying to do
I'm sorry for being unclear. I am trying to index the location of a randomly chosen value within a NumPy array containing identical values.
Well, the code I write will also work for a random value.
0

This will give you your desired output:

np.where(a==b)[0][0]

Comments

0

NumPy's where() function does what you want, as described in other answers. If you only have 1D arrays and you only want the index of the first element in a which equals b, where() is both clunky and inefficient. Instead, you may use

import numpy as np
a = np.linspace(1, 10, 10)  # Hint: the np.array() is superfluous
b = np.random.choice(a)
index = next(i for i, el in enumerate(a) if el == b)
print(index, a[index])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.