Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Index of element in NumPy array [duplicate]

In Python we can get the index of a value in an array by using .index().

But with a NumPy array, when I try to do:

decoding.index(i) 

I get:

AttributeError: 'numpy.ndarray' object has no attribute 'index'

How could I do this on a NumPy array?

like image 478
Marc Ortiz Avatar asked Aug 06 '13 11:08

Marc Ortiz


People also ask

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

int[] arr = {3,5,6,7,2,3,11,14 }; int index = Array. IndexOf(arr, 3); Console. WriteLine(index); Console. ReadLine();

Does indexing a NumPy array create a copy?

Boolean indexing returns a copy of the data, not a view of the original data, like one gets for slices. I can manipulate b and data is preserved. However, as you've identified, assignments made via indexed arrays are always made to the original data.

Does NumPy array have index?

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.


2 Answers

Use np.where to get the indices where a given condition is True.

Examples:

For a 2D np.ndarray called a:

i, j = np.where(a == value) # when comparing arrays of integers  i, j = np.where(np.isclose(a, value)) # when comparing floating-point arrays 

For a 1D array:

i, = np.where(a == value) # integers  i, = np.where(np.isclose(a, value)) # floating-point 

Note that this also works for conditions like >=, <=, != and so forth...

You can also create a subclass of np.ndarray with an index() method:

class myarray(np.ndarray):     def __new__(cls, *args, **kwargs):         return np.array(*args, **kwargs).view(myarray)     def index(self, value):         return np.where(self == value) 

Testing:

a = myarray([1,2,3,4,4,4,5,6,4,4,4]) a.index(4) #(array([ 3,  4,  5,  8,  9, 10]),) 
like image 191
Saullo G. P. Castro Avatar answered Sep 28 '22 08:09

Saullo G. P. Castro


You can convert a numpy array to list and get its index .

for example:

tmp = [1,2,3,4,5] #python list a = numpy.array(tmp) #numpy array i = list(a).index(2) # i will return index of 2, which is 1 

this is just what you wanted.

like image 32
Statham Avatar answered Sep 28 '22 09:09

Statham