Python 2D array replace value by NaN when other array is NaN

  arrays, mask, nan, python

I have 2 arrays:

import numpy as np
A = np.array([[np.nan,np.nan,0],[4,5,6],[7,8,9]])
B = np.zeros((len(A),len(A[0])))

For every NaN in A, I would like to replace the zero in B at the corresponding indices by np.nan. How can I do that ? I tried with masks but couldn’t make it work.

B = np.ma.masked_where(np.isnan(A) == True, np.nan) 

In reality I am working with bigger arrays (582×533) so I don’t want to do it by hand.

Source: Python Questions

LEAVE A COMMENT