-2

I want to ask a question about finding the position of an element within an array in Python's numpy package.

I am using Jupyter Notebook for Python 3 and have the following code illustrated below:

concentration_list = array([172.95, 173.97, 208.95])

and I want to write a block of code that would be able to return the position of an element within the array.

For this purpose, I wanted to use 172.95 to demonstrate.

Initially, I attempted to use .index(), passing in 172.95 inside the parentheses but this did not work as numpy does not recognise the .index() method -

concentration_position = concentration_list.index(172.95)

AttributeError: 'numpy.ndarray' object has no attribute 'index'

The Sci.py documentation did not mention anything about such a method being available when I accessed the site.

Is there any function available (that I may not have discovered) to solve the problem?

vik1245
  • 546
  • 2
  • 9
  • 26
  • Does this answer your question? [Is there a NumPy function to return the first index of something in an array?](https://stackoverflow.com/questions/432112/is-there-a-numpy-function-to-return-the-first-index-of-something-in-an-array) – AMC Feb 06 '20 at 23:15

2 Answers2

2

You can go through the where function from the numpy library

import numpy as np

concentration_list = np.array([172.95, 173.97, 208.95])
number = 172.95

print(np.where(concentration_list == number)[0])


Output : [0]
Julien Drevon
  • 322
  • 2
  • 17
  • 1
    From the docs for [`numpy.where()`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html): _When only condition is provided, this function is a shorthand for np.asarray(condition).nonzero(). Using nonzero directly should be preferred, as it behaves correctly for subclasses._ – AMC Feb 06 '20 at 23:19
1

Use np.where(...) for this purpose e.g.

import numpy as np

concentration_list = np.array([172.95, 173.97, 208.95])

index=np.ravel(np.asarray(concentration_list==172.95).nonzero())

print(index)

#outputs (array of all indexes matching the condition):

>> [0]
Grzegorz Skibinski
  • 12,624
  • 2
  • 11
  • 34
  • 1
    From the docs for [`numpy.where()`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html): _When only condition is provided, this function is a shorthand for np.asarray(condition).nonzero(). Using nonzero directly should be preferred, as it behaves correctly for subclasses._ – AMC Feb 06 '20 at 23:19
  • Tweaked! Cheers! – Grzegorz Skibinski Feb 06 '20 at 23:24