Royal
Royal

Reputation: 115

Create a mask according to the value of a numpy array

My purpose is to create a mask of a numpy array according to the change in the values of the array.

Example:

A = np.array([[1,1,1,1,1], [1,8,7,10,1], [1,9,1,7,1],[1,8,10,9,1],[1,1,1,1,1]])
A = 
 [[ 1  1  1  1  1]
 [ 1  8  7 10  1]
 [ 1  9  1  7  1]
 [ 1  8 10  9  1]
 [ 1  1  1  1  1]]

and the mask would be:

[ 0  0  0  0  0]
[ 0  1  1  1  0]
[ 0  1  1  1  0]
[ 0  1  1  1  0]
[ 0  0  0  0  0]

As you see I want to create a mask that keep where the value of the array increase and keep the inside.

I tried to iterate by column with this:

for column in a.T:
    print(column)

but I don't know how I can check where values are increasing and how can I create a numpy array with 0 1 placed accordingly

Thanks

Upvotes: 1

Views: 190

Answers (1)

Kevin
Kevin

Reputation: 3348

This might work:

dx = np.diff(A, prepend=A[:,[0]], axis=1)
dy = np.diff(A, prepend=A[[0],:], axis=0)

(dx * dy != 0).astype(int)

Output:

array([[[0, 0, 0, 0, 0],
        [0, 1, 1, 1, 0],
        [0, 1, 1, 1, 0],
        [0, 1, 1, 1, 0],
        [0, 0, 0, 0, 0]]])

Upvotes: 1

Related Questions