-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))
codingishard
  • 15
  • 1
  • 5
  • I am not sure index function works with arrays, try this link: https://stackoverflow.com/questions/18079029/index-of-element-in-numpy-array – Lhooplala Nov 12 '19 at 13:06

3 Answers3

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.

Yohann L.
  • 1,262
  • 13
  • 27
  • 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. – codingishard Nov 12 '19 at 13:19
  • 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) – codingishard Nov 12 '19 at 13:35
  • I don't understand what you're trying to do – Yohann L. Nov 12 '19 at 13:39
  • 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. – codingishard Nov 12 '19 at 13:48
  • Well, the code I write will also work for a random value. – Yohann L. Nov 12 '19 at 13:53
0

This will give you your desired output:

np.where(a==b)[0][0]
zipa
  • 27,316
  • 6
  • 40
  • 58
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])
jmd_dk
  • 12,125
  • 9
  • 63
  • 94