Kallol Das
Kallol Das

Reputation: 89

What is fastest way to check conditions in two python numpy arrays?

Is there any way to make the below code faster?

for q in range (1155):
  for p in range(1683):
    if original_data[q, p] == 0 and rain100[q, p] == 0:
      original_data[q, p] = np.nan
      rain100[q, p] = np.nan

Here I am dealing with two arrays. If we deal with only one array, I think, we can make it faster. For example,

original_data[original_data == 0] = np.nan

I think this is much faster than running a loop index by index.

Is there any way to do the similar kind of thing if we deal with two arrays?

Upvotes: 1

Views: 230

Answers (1)

Julien
Julien

Reputation: 15071

Defining a boolean mask with 2 (or more) arrays is as easy:

mask = (original_data == 0) & (rain100 == 0)
original_data[mask] = np.nan
rain100[mask] = np.nan

Upvotes: 4

Related Questions