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


Python numpy.ma.where()用法及代碼示例

numpy.ma.where()函數根據條件返回具有x或y元素的掩碼數組。

用法: numpy.ma.where(condition, x, y) 

參數:
condition:[數組,bool]如果為True,則產生x,否則產生y。
x, y:[數組,可選]從中選擇的值。 x,y和條件必須廣播到某種形狀。

Return :[MaskedArray]一個帶有被遮罩的元素(其中條件被遮罩),來自x的元素(其中條件為True)以及來自y的元素的遮罩數組。

代碼1:



# Python program explaining 
# numpy.ma.where() function 
   
# importing numpy as geek  
# and numpy.ma module as ma  
import numpy as geek  
import numpy.ma as ma 
    
x = geek.ma.array(geek.arange(4.).reshape(2, 2),  
                        mask =[[0, 1], [1, 0]]) 
  
gfg = geek.ma.where(x > 5, x, -3.1416) 
   
print (gfg)

輸出:

[[-3.1416 --]
 [-- -3.1416]]


代碼2:

# Python program explaining 
# numpy.ma.where() function 
   
# importing numpy as geek  
# and numpy.ma module as ma  
import numpy as geek  
import numpy.ma as ma 
    
x = geek.ma.array(geek.arange(9.).reshape(3, 3),  
       mask =[[0, 1, 0], [1, 0, 1], [0, 1, 0]]) 
  
gfg = geek.ma.where(x > 5, x, -3.1416) 
   
print (gfg)

輸出:

[[-3.1416 -- -3.1416]
 [-- -3.1416 --]
 [6.0 -- 8.0]]



相關用法


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