# Numpy 修炼之道 （11）—— 掩码数组

2年前 阅读 295 点赞 0

>>> import numpy as np

>>> import numpy.ma as ma

>>> x = np.array([1, 2, 3, -99, 5])

>>> x

array([  1,   2,   3, -99,   5])

0, 0, 1, 0])

>>> mx

masked_array(data = [1 2 3 -- 5],

mask = [False False False True False],

fill_value = 999999)

>>> mx.mean()

2.75

访问掩码

>>> mx

masked_array(data = [1 2 3 -- 5],

mask = [False False False  True False],

fill_value = 999999)

array([False, False, False,  True, False], dtype=bool)

只访问有效数据

>>> x = ma.array([[1, 2], [3, 4]],

fill_value = 999999)

>>> x.compressed()

array([1, 4])

修改掩码

>>> x = ma.array([1, 2, 3], mask=[0,0, 1])

>>> x

mask = [ True  True  True],

fill_value = 999999)

>>> x = ma.array([1, 2, 3])

>>> x.mask = [0, 1, 0]

>>> x

fill_value = 999999)

取消掩码

>>> x = ma.array([1, 2, 3], mask=[0,0, 1])

>>> x

fill_value = 999999)

>>> x[-1] = 5

>>> x

fill_value = 999999)

>>> x = ma.array([1, 2, 3], mask=[0,0, 1])

>>> x

fill_value = 999999)

>>> x

fill_value = 999999)

索引和切片

>>> x = ma.array([1, 2, 3], mask=[0,0, 1])

>>> x[0]

1

>>> x[-1]

fill_value = 1e+20)

True

...

...

dtype=[('a', int), ('b', int)])

>>> y[0]

(1, 2)

>>> y[-1]

fill_value = (999999,999999),

dtype = [('a', '<i4'), ('b', '<i4')])

>>> x = ma.array([1, 2, 3, 4, 5],

>>> mx = x[:3]

>>> mx

fill_value = 999999)

>>> mx[1] = -1

>>> mx

fill_value = 999999)