I am looking for a NumPy array function that functions the same as index() in the list

Asked 2 years ago, Updated 2 years ago, 47 views

Usually, in Python lists,

l = list(1,2,3)
l.index(2)

I'm using index(x) to find the location of item x, but I can't find this function in NumPyarray

python array numpy

2022-09-22 13:28

1 Answers

In numpy, numpy.Write where (condition[,x,y]).

Returns the tuple datatype as a result.

import numpy

myarr = numpy.array([4,3,2,1,4,6,2], int)
arridx = numpy.where(myarr == 4)

numpy.Where is not exactly the same as index.

For example, if you have multiple elements you want to find, the index only finds the first index, but numpy.where finds the index of all elements.

mylist = [4,3,2,4,6,2]
listidx = mylist.index(4)
print(listidx) #0 only output

import numpy

myarr = numpy.array([4,3,2,4,6,2], int)
arridx = numpy.where(myarr == 4)
print(arridx) #(array([0,3]), output

Also, if you set the list/array to two dimensions, the index does not find the element when you look for elements in the embedded list.

import numpy

myarr = numpy.array([[4,3,2],[4,6,2]], int)
arridx = numpy.where(myarr == 4)
print(arridx) #(array([0,1]), array([0,0]))) output

mylist = [[4,3,2],[4,6,2]]
ValueError because listidx = mylist.index(4) #4 is missing
print(listidx)


2022-09-22 13:28

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.