Search code examples
pythonarraysnumpymasking

Python - replace masked data in arrays


I would like to replace by zero value all my masked values in 2D array. I saw with np.copyto it was apparently possible to do that as :

test=np.copyto(array, 0, where = mask)

But i have an error message...'module' object has no attribute 'copyto'. Is there an equivalent way to do that?


Solution

  • Try numpy.ma.filled() I think this is exactly what you need

    In [29]: a
    Out[29]: array([ 1,  0, 25,  0,  1,  4,  0,  2,  3,  0])
    In [30]: am = n.ma.MaskedArray(n.ma.log(a),fill_value=0)
    In [31]: am
    Out[31]: 
    masked_array(data = [0.0 -- 3.2188758248682006 -- 0.0 1.3862943611198906 --  0.6931471805599453  1.0986122886681098 --], 
    mask = [False  True False  True False False  True False False  True],
    fill_value = 0.0)
    In [32]: am.filled()
    Out[32]: 
    array([ 0.        ,  0.        ,  3.21887582,  0.        ,  0.        ,
        1.38629436,  0.        ,  0.69314718,  1.09861229,  0.        ])