2

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,).

2 Answers 2

2

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.]])
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.