import numpy as np
foo = [1, "hello", np.array([[1,2,3]]) ]
I would expect
foo.index( np.array([[1,2,3]]) )
to return
2
but instead I get
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
anything better than my current solution? It seems inefficient.
def find_index_of_array(list, array):
for i in range(len(list)):
if np.all(list[i]==array):
return i
find_index_of_array(foo, np.array([[1,2,3]]) )
# 2
Use the List index() Method to Find the Index of a List in Python. Python list has a built-in method called index() , which accepts a single parameter representing the value to search within the existing list.
To find the index of an element in a list, you use the index() function. It returns 3 as expected.
To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found.
The reason for the error here is obviously because numpy's ndarray overrides ==
to return an array rather than a boolean.
AFAIK, there is no simple solution here. The following will work so long as the np.all(val == array)
bit works.
next((i for i, val in enumerate(lst) if np.all(val == array)), -1)
Whether that bit works or not depends critically on what the other elements in the array are and if they can be compared with numpy arrays.
How about this one?
arr = np.array([[1,2,3]])
foo = np.array([1, 'hello', arr], dtype=np.object)
# if foo array is of heterogeneous elements (str, int, array)
[idx for idx, el in enumerate(foo) if type(el) == type(arr)]
# if foo array has only numpy arrays in it
[idx for idx, el in enumerate(foo) if np.array_equal(el, arr)]
Output:
[2]
Note: This will also work even if foo
is a list. I just put it as a numpy
array here.
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