简体   繁体   中英

Masking only non-NaN values (Python)

I have a multidimensions matrix and want to mask all values which are NOT NaN values. I know there is a mask for invalid where one can mask NaN values but I want the opposite - to only want to keep the NaN values. I've tried using where but am not sure if I am writing it correctly.

Code, tt & tt2 produce (same thing)

tt = np.ma.array([[[0,1,2],[3,np.nan,5],[6,7,8]], 
             [[10,11,12],[13,np.nan,15],[16,17,18]],
              [[20,21,22],[23,np.nan,25],[26,27,28]]])
tt2 = np.ma.where(tt == np.nan, tt == np.nan, tt)

[[[ 0.  1.  2.]
  [ 3. nan  5.]
  [ 6.  7.  8.]]

  [[10. 11. 12.]
   [13. nan 15.]
   [16. 17. 18.]]

  [[20. 21. 22.]
   [23. nan 25.]
   [26. 27. 28.]]]

Desired Result: All integers to be masked (--), leaving only Nan

I think you want:

tt2 = np.ma.masked_where(~np.isnan(tt), tt)

Note the use of np.isnan (ie, note that np.NaN == np.NaN is False !), and the not ( ~ ) operator. In other words, this does, "mask where the array tt is not NaN". Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM