(2)python_numpy: numpy.ma.masked_invalid 与 numpy.ma.compress_rowcols 函数用法

1, numpy.ma.masked_invalid(a, copy=True)

Mask an array where invalid values occur (NaNs or infs).
参数a为一个数组。
当数组a中某些元素为无效值(NaNs or infs)时,则将无效值的元素设置为mask(–)。

如:
在这里插入图片描述


2, numpy.ma.compress_rowcols(x, axis=None)

在这里插入图片描述
参数
x:
    被mask的数组(数组内被mask的元素可以为0个或多个);
axis:
    默认为None,则数组内被mask的元素所在的行与列都会被屏蔽,
    axis=0,则数组内被mask的元素所在的行被屏蔽,
    axis=1,则数组内被mask的元素所在的列被屏蔽。

返回值
返回被屏蔽完成以后的数组(ndarray)。


example:

def np_masked_test():
    # make mask 1
    arr1 = np.arange(0, 9, dtype=float).reshape(3, 3)
    arr1[0][1] = np.NAN  # 无效值
    arr1[1][0] = np.PINF  # 无效值
    print('arr1:\n', '{arr1}'.format(arr1=arr1))
    arr1_m = np.ma.masked_invalid(arr1)  # 把数组arr1中的无效值设置为masked(用--表示)
    print('arr1_m:\n', '{arr1_m}'.format(arr1_m=arr1_m))

    # make mask 2
    x = np.ma.array(np.arange(9).reshape(3, 3), mask=[[1, 0, 0],
                                                      [1, 0, 0],
                                                      [0, 0, 0]])
    print('x:\n', '{}'.format(x))
    # ---------

    # 1,remove rows and cols which are masked
    supress_defalut = np.ma.compress_rowcols(arr1_m)  # 把arr1中设置为mask的元素所在的行与列进行屏蔽。
    print('supress_defalut:\n', '{supress_defalut}'.format(supress_defalut=supress_defalut))


    # 2,remove rows which are masked
    supress_rows = np.ma.compress_rowcols(arr1_m, 0)  # axis为0,则 rows are supressed
    print('supress_rows:\n', '{supress_rows}'.format(supress_rows=supress_rows))
    supress_rows1 = np.ma.compress_rows(arr1_m)  # 与axis为0相同,rows are supressed
    print('supress_rows1:\n', '{supress_rows1}'.format(supress_rows1=supress_rows1))

    # 3,remove cols which are masked
    supress_cols = np.ma.compress_rowcols(arr1_m, 1)  # axis为1,则列被屏蔽
    print('supress_cols:\n', '{supress_cols}'.format(supress_cols=supress_cols))
    supress_cols1 = np.ma.compress_cols(arr1_m)  # 与axis为1相同,列被屏蔽
    print('supress_cols1:\n', '{supress_cols1}'.format(supress_cols1=supress_cols1))

if __name__ == '__main__':
    np_masked_test()

打印:

arr1:
 [[ 0. nan  2.]
 [inf  4.  5.]
 [ 6.  7.  8.]]
arr1_m:
 [[0.0 -- 2.0]
 [-- 4.0 5.0]
 [6.0 7.0 8.0]]
x:
 [[-- 1 2]
 [-- 4 5]
 [6 7 8]]
supress_defalut:
 [[8.]]
supress_rows:
 [[6. 7. 8.]]
supress_rows1:
 [[6. 7. 8.]]
supress_cols:
 [[2.]
 [5.]
 [8.]]
supress_cols1:
 [[2.]
 [5.]
 [8.]]
©️2020 CSDN 皮肤主题: 游动-白 设计师:上身试试 返回首页