Pramod
Pramod

Reputation: 89

FIlter the multi-D array based other same size array

I have two arrays of gridded data 'A' and 'B' of the same dimensions (1440, 400). I want to create a new array 'C' of the same dimension (1440, 400) where C contains the values from grid points of A that are only greater than B for the same grid point. If A < B, the values of A need to be replaced by NaN in C. Using the following code

C = A[A>B]

gives a one-dimensional array. In my case, it gives an array of shape (2362,).

Upvotes: 2

Views: 99

Answers (2)

jss367
jss367

Reputation: 5371

I think np.where(A>B, A, np.nan) is what you're looking for. That will give you A when the condition (A>B) is True and B when it is False. Here's an example:

import numpy as np
A = np.ones((1440, 400))
B = np.zeros((1440, 400))
B[0, 0] = 3
C = np.where(A>B, A, np.nan)

This gives:

array([[nan, 1., 1., ..., 1., 1., 1.],
       [1., 1., 1., ..., 1., 1., 1.],
       [1., 1., 1., ..., 1., 1., 1.],
       ...,
       [1., 1., 1., ..., 1., 1., 1.],
       [1., 1., 1., ..., 1., 1., 1.],
       [1., 1., 1., ..., 1., 1., 1.]])

EDIT: I misread how the final result should be so I updated this.

Upvotes: 1

iz_
iz_

Reputation: 16573

You can use np.where to replace values where A > B is False with np.nan:

In [1]: import numpy as np

In [2]: A = np.arange(9).reshape(3, 3)

In [3]: B = np.full((3, 3), 4)

In [4]: np.where(A > B, A, np.nan)
Out[4]:
array([[nan, nan, nan],
       [nan, nan,  5.],
       [ 6.,  7.,  8.]])

Upvotes: 2

Related Questions