Find index of numpy array in list
Can someone explain why the following is happening? 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 l
can find the index a
, but not b
?
+3
source to share
2 answers
Applying the idea at fooobar.com/questions/1491903 / ... (see the "Linked side" section)
[np.array_equal(b,x) for x in l].index(True)
should be more reliable. It provides the correct array for array comparison.
Or [id(b)==id(x) for x in l].index(True)
if you want it to compare IDs.
+4
source to share