(2)python_numpy: numpy.ma.masked_invalid 與 numpy.ma.compress_rowcols 函式用法

小旺的尾巴發表於2020-09-25

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.]]

相關文章