Search code examples
pythonarraysnumpy2d

How to find specific elements in 2d array?


a2D = np.arraya2D = np.array([[1, 2, 3, 2, 1], [1, 4, 5, 3, 2]])

So if I have an array such as this I am not sure if it's possible to find a specific part of the array in which values are larger than its neighbor so if it finds that 3 and 5 are the values I would like it to print/return the array position so a2D[0][2], a2D[1][2]


Solution

  • You can try to traverse each element in your a2D array and check if the current element is greater than its neighbours (using 2 for loops):

    import numpy as np
    
    a2D = np.arraya2D = np.array([[1, 2, 3, 2, 1], [1, 4, 5, 3, 2]])
    
    for i in range(len(a2D)):
        for j in range(1, len(a2D[i])-1):
            if a2D[i][j] > a2D[i][j-1] and a2D[i][j] > a2D[i][j+1]:
                print('a2D[{}][{}]'.format(i,j))
                break
    

    Output:

    a2D[0][2]
    a2D[1][2]
    

    I am assuming that such an element is unique, that's why the break. If that is not the case, the break would not be there.