Home > Net >  numpy - conditional change with closest elements
numpy - conditional change with closest elements

Time:06-25

In a numpy array, I want to replace every occurrences of 4 where top and left of them is a 5.

so for instance :

0000300 
0005000
0054000
0000045
0002050

Should become :

0000300
0005000
0058000
0000045
0002000

I'm sorry I can't share what I tried, that's a very specific question.

I've had a look at things like

map[map == 4] = 8

And np.where() but I have really no idea about how to check nearby elements of a specific value.

CodePudding user response:

this might seem tricky, but an and between three shifted versions of the matrix will work, you simply need to shift the x==5 array to the bottom, and another version will shift to the right, the third matrix is the x==4.

first_array = np.zeros(x.shape,dtype=bool)
second_array = np.zeros(x.shape,dtype=bool)
equals_5 = x == 5
equals_4 = x == 4
first_array[1:] = equals_5[:-1] # shift down
second_array[:,1:] = equals_5[:,:-1] # shift right 
third_array = equals_4 # put it as it is.
# ie: and operation on the 3 arrays above
results = np.logical_and(np.logical_and(first_array,second_array),third_array)
x[results] = 8

now results will be the needed logical array. and it's an O(n) algorithm, but it scales badly if the requested pattern is very complex, not that it's not doable.

  • Related