Index of element in NumPy array

2019-01-16 18:28发布

In Python we can get the index of a value in an array by using .index(). How can I do it with a NumPy array?

When I try to do

decoding.index(i)

it says that the NumPy library doesn't support this function. Is there a way to do it?

4条回答
ゆ 、 Hurt°
2楼-- · 2019-01-16 19:14

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.

查看更多
Ridiculous、
3楼-- · 2019-01-16 19:15

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 second method returns an int, instead of a nparray.

查看更多
闹够了就滚
4楼-- · 2019-01-16 19:32

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

i is just what you want.

查看更多
The star\"
5楼-- · 2019-01-16 19:34

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

Examples:

For a 2D np.ndarray:

i, j = np.where(a == value)

For a 1D array:

i, = np.where(a == value)

Which 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]),)
查看更多
登录 后发表回答