简体   繁体   中英

Numpy: Masked elements in computation

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

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

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