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
?
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.
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).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With