Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Append Masked Arrays

Tags:

python

numpy

I have two arrays, and I want to append them into a new array but I need the masked information to be kept. I tried numpy.append(), but it lose the masked information.

>>> maska
masked_array(data = [-- 1 3 2 1 -- -- 3 6],
     mask = [ True False False False False  True  True False False],
     fill_value = 0)

>>> b
masked_array(data = [-- 1 3 2],
     mask = [ True False False False], fill_value = 0)

>>> np.append(maska,b)
masked_array(data = [0 1 3 2 1 0 0 3 6 0 1 3 2],
     mask = False, fill_value = 999999)
like image 474
CJJ Avatar asked Oct 20 '22 09:10

CJJ


1 Answers

This is indeed very strange that even np.ma.hstack doesn't work, but you can achieve what you need by manually combining the masks:

In [1]: import numpy as np

In [2]: def masked_hstack(tup):
   ...:     return np.ma.masked_array(np.hstack(tup),
   ...:            mask=np.hstack([arr.mask for arr in tup]))
   ...:

In [3]: a, b = [0, 1, 3, 2, 1, 0, 0, 3, 6], [0, 1, 3, 2]

In [4]: maska, maskb = [np.ma.masked_equal(arr, 0) for arr in a, b]

In [5]: masked_hstack((maska, maskb))
Out[5]:
masked_array(data = [-- 1 3 2 1 -- -- 3 6 -- 1 3 2],
             mask = [ True False False False False  True  True False False  True False False
 False],
       fill_value = 999999)

You can also override the fill_value to be 0, if that matters.

like image 128
Lev Levitsky Avatar answered Oct 23 '22 09:10

Lev Levitsky