I would like to check a condition inside an array and perform an operation on the position where the condition is met. For example, this piece of code does the job:
res = somefunction(x)
for i in range(x.shape[0]):
for j in range(x.shape[1]):
if not 6 < res[i,j] < 18:
x[i,j] = float('nan')
But I thought a faster (and shorter) way would maybe be something like this:
x[not 6 < somefunction(x) < 18] = float('nan')
But python gives the error that condition checking doesn't work in array with more than element. Is there a way to make my code go faster?
x[~((6 < x) & (x < 18))] = np.nan
may work?