Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the index of a numpy array in a list

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
like image 265
Lee88 Avatar asked Dec 21 '16 21:12

Lee88


People also ask

How do you find the index of an array in a list in Python?

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.

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.

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

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.


2 Answers

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.

like image 150
mgilson Avatar answered Sep 29 '22 23:09

mgilson


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.

like image 23
kmario23 Avatar answered Sep 30 '22 00:09

kmario23