Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find index of numpy array in list

Can someone explain why the following occurs? My use case is that I have a python list whose elements are all numpy ndarray objects and I need to search through the list to find the index of a particular ndarray obj.

Simplest Example:

>>> import numpy as np
>>> a,b = np.arange(0,5), np.arange(1,6)
>>> a
array([0, 1, 2, 3, 4])
>>> b
array([1, 2, 3, 4, 5])
>>> l = list()
>>> l.append(a)
>>> l.append(b)
>>> l.index(a)
0
>>> l.index(b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Why can l find the index of a, but not b?

like image 458
waldol1 Avatar asked May 19 '15 17:05

waldol1


People also ask

How do you find the index of an element in a NumPy array?

Using ndenumerate() function to find the Index of value It is usually used to find the first occurrence of the element in the given numpy array.

How do you find the index of an array in python?

Python has a method to search for an element in an array, known as index(). If you would run x. index('p') you would get zero as output (first index).

How do you find the index of a value in a list python?

To find the index of an element in a list, you use the index() function. It returns 3 as expected. However, if you attempt to find an element that doesn't exist in the list using the index() function, you'll get an error. To fix this issue, you need to use the in operator.

Can you index a NumPy array?

Array indexing is the same as accessing an array element. You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.


1 Answers

Applying the idea in https://stackoverflow.com/a/17703076/901925 (see the Related sidebare)

[np.array_equal(b,x) for x in l].index(True)

should be more reliable. It ensures a correct array to array comparison.

Or [id(b)==id(x) for x in l].index(True) if you want to ensure it compares ids.

like image 65
hpaulj Avatar answered Sep 29 '22 13:09

hpaulj