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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With