Index of element in NumPy array [duplicate]
Asked Answered
M

6

118

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?

Mokpo answered 6/8, 2013 at 11:32 Comment(0)
H
184

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]),)
Haematoma answered 6/8, 2013 at 11:38 Comment(2)
Why have the commata after the variable names in the 1D cases? Just in case the input is bad?Foreign
@BUFU, that's because the output of np.where is always a tuple. If I used i = np.where(...), my variable i would be a tuple objectHaematoma
A
33

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.

Autocephalous answered 10/4, 2018 at 1:46 Comment(0)
Y
18

I'm torn between these two ways of implementing an index of a NumPy array:

idx = list(classes).index(var)
idx = np.where(classes == var)

Both take the same number of characters, but the first method returns an int instead of a numpy.ndarray.

Yod answered 27/5, 2016 at 14:32 Comment(1)
idx = list(classes).index(var) <----- This is awesome!Saintpierre
P
10

This problem can be solved efficiently using the numpy_indexed library (disclaimer: I am its author); which was created to address problems of this type. npi.indices can be viewed as an n-dimensional generalisation of list.index. It will act on nd-arrays (along a specified axis); and also will look up multiple entries in a vectorized manner as opposed to a single item at a time.

a = np.random.rand(50, 60, 70)
i = np.random.randint(0, len(a), 40)
b = a[i]

import numpy_indexed as npi
assert all(i == npi.indices(a, b))

This solution has better time complexity (n log n at worst) than any of the previously posted answers, and is fully vectorized.

Piperonal answered 5/2, 2019 at 14:35 Comment(0)
L
5

You can use the function numpy.nonzero(), or the nonzero() method of an array

import numpy as np

A = np.array([[2,4],
          [6,2]])
index= np.nonzero(A>1)
       OR
(A>1).nonzero()

Output:

(array([0, 1]), array([1, 0]))

First array in output depicts the row index and second array depicts the corresponding column index.

Lafountain answered 15/1, 2019 at 6:25 Comment(0)
I
2

If you are interested in the indexes, the best choice is np.argsort(a)

a = np.random.randint(0, 100, 10)
sorted_idx = np.argsort(a)
Incautious answered 23/2, 2019 at 18:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.