Numpy: Masked elements in computation

2019-06-06 03:03发布

问题:

I have a function to built a polynomial from a given x: [1, x^2,x^3,x^4,...,x^degree]

def build_poly(x, degree):
    """polynomial basis functions for input data x, for j=0 up to j=degree."""
    D = len(x)
    polyome = np.ones((D, 1))
    for i in range(1, degree+1):
        polyome = np.c_[polyome, x**i]

    return polyome

Now, I would like to calculate polynom for a given x, but omiting sume values.

Hence, what this is what I did:

Created X:

x=np.array([[1,2,3],[4,5,6]])])

I masked away the value with I wanted to omit:

masked_x= np.ma.masked_equal(x, 5)
print(masked_x)

But when I do the computation:

print(build_poly(masked_x,2))

The masking has disappeeared. Why ? I want to have the program omit the masked elements

回答1:

Apparently when working with masked arrays one must consistently use the numpy.ma versions of the routines. Any departure from this, and numpy 'forgets' that masked elements are present.

def build_poly(x, degree):
    """polynomial basis functions for input data x, for j=0 up to j=degree."""
    D = len(x)
    polyome = np.ones((D, 1))
    for i in range(1, degree+1):
        polyome = np.ma.concatenate([polyome, np.ma.power(x,i)], axis=1)
    return polyome