Retrieve position of elements with setting some criteria in numpy

后端 未结 4 901
没有蜡笔的小新
没有蜡笔的小新 2021-01-13 22:24

For the given 2d array of data, how to retrieve the position (index) of 7 and 11 in the bold. Because only they are the elements surrounded by same value in the neighbours

4条回答
  •  生来不讨喜
    2021-01-13 22:40

    I used a list comprehension but there may be a better way

    A = [(i,j) for i in range(1,data.shape[0]-1) for j in range(1,data.shape[1]-1) if all((data[i-1:i+2,j-1:j+2]==data[i,j]).flatten())]
    

    EDIT:

    If you want the form array([i,j],dtype=int64) then you just need to modify the first part:

    A= [np.array([i,j], dtype=np.int64) for i in range(1,data.shape[0]-1) for j in range(1,data.shape[1]-1) if all((data[i-1:i+2,j-1:j+2]==data[i,j]).flatten())]
    

提交回复
热议问题