當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python Numpy MaskedArray.masked_where()用法及代碼示例


在許多情況下,數據集可能不完整或被無效數據汙染。例如,傳感器可能無法記錄數據或記錄了無效值。的numpy.ma模塊通過引入掩碼數組提供了解決此問題的便捷方法。掩碼數組是可能缺少條目或無效條目的數組。

numpy.MaskedArray.masked_where()函數用於屏蔽滿足條件的數組,它返回arr作為條件為True時被屏蔽的數組。任何arr或condition的掩碼值也將在輸出中被掩碼。

用法: numpy.ma.masked_where(condition, arr, copy=True)

參數:
condition :[數組]屏蔽條件。當條件測試浮點值是否相等時,請考慮改用masked_values。
arr :[ndarray]我們要屏蔽的輸入數組。
copy :[bool]如果為True(默認),則在結果中複製arr。如果為False,則修改arr並返回視圖。

Return :[MaskedArray]對條件為True的arr進行掩碼的結果。

代碼1:

# Python program explaining 
# numpy.MaskedArray.masked_where() method  
  
# importing numpy as geek  
# and numpy.ma module as ma 
import numpy as geek 
import numpy.ma as ma 
  
# creating input array  
in_arr = geek.array([1, 2, 3, -1, 2]) 
print ("Input array:", in_arr) 
  
# applying MaskedArray.masked_where methods  
# to input array where value<= 1 
mask_arr = ma.masked_where(in_arr<= 1, in_arr) 
print ("Masked array:", mask_arr)
輸出:
Input array: [ 1  2  3 -1  2]
Masked array: [-- 2 3 -- 2]

代碼2:

# Python program explaining 
# numpy.MaskedArray.masked_where() method  
  
# importing numpy as geek  
# and numpy.ma module as ma 
import numpy as geek 
import numpy.ma as ma 
  
# creating input array in_arr1  
in_arr1 = geek.arange(4) 
print ("1st Input array:", in_arr1) 
  
# applying MaskedArray.masked_where methods  
# to input array in_arr1 where value = 1 
mask_arr1 = ma.masked_where(in_arr1 == 1, in_arr1) 
print ("1st Masked array:", mask_arr1) 
  
# creating input array in_arr2  
in_arr2 = geek.arange(4) 
print ("2nd Input array:", in_arr2) 
  
# applying MaskedArray.masked_where methods  
# to input array in_arr2 where value = 1 
mask_arr2 = ma.masked_where(in_arr2 == 3, in_arr2) 
print ("2nd Masked array:", mask_arr2) 
  
# applying MaskedArray.masked_where methods  
# to 1st masked array where second masked array 
# is used as condition 
res_arr = ma.masked_where(mask_arr1 == 3, mask_arr2) 
print("Resultant Masked array:", res_arr)
輸出:
1st Input array: [0 1 2 3]
1st Masked array: [0 -- 2 3]
2nd Input array: [0 1 2 3]
2nd Masked array: [0 1 2 --]
Resultant Masked array: [0 -- 2 --]


相關用法


注:本文由純淨天空篩選整理自jana_sayantan大神的英文原創作品 Numpy MaskedArray.masked_where() function | Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。