-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?

1

2 Answers 2

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]
Sign up to request clarification or add additional context in comments.

1 Comment

From the docs for numpy.where(): 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.
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]

2 Comments

From the docs for numpy.where(): 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.
Tweaked! Cheers!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.