简体   繁体   中英

Is there a way to find every index of an input value in a 2d array?

I've been trying to make a function in python that returns the x,y coordinate of every recurring value in a 2d array. For example if I had the array and a value,

array = [ [1 ,2 ,3]
          [2 ,3 ,1]
          [3 ,2, 1]]

search = 1

it would output (0,0) (1,2) (2,2)

I've been trying to use some functions such as np.where or converting it into a pandas data frame and searching that way, but I'm not sure the best way to do it. When I use np.where, it returns an empty array because I'm using long decimals. I'm trying to do this on an array thats 200 x 200.

We can do np.where PS: a is your array

list(zip(*np.where(a==search)))
[(0, 0), (1, 2), (2, 2)]

As hpaulj mentioned

np.argwhere(np.isclose(a,search))
array([[0, 0],
       [1, 2],
       [2, 2]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM