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


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


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

numpy.MaskedArray.astype()函數返回MaskedArray強製類型轉換為給定新類型的副本。

用法: numpy.MaskedArray.astype(newtype)

參數:
newtype :我們要在其中轉換掩碼數組的類型。

Return :[MaskedArray]自我轉換的副本,用於輸入新類型。返回的記錄形狀與self.shape匹配。

代碼1:

# Python program explaining 
# numpy.MaskedArray.astype() 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, 5]) 
print ("Input array:", in_arr) 
  
# Now we are creating a masked array of int32  
# and making third entry as invalid.  
mask_arr = ma.masked_array(in_arr, mask =[0, 0, 1, 0, 0]) 
print ("Masked array:", mask_arr) 
  
# printing the data type of masked aaray 
print(mask_arr.dtype)  
  
# applying MaskedArray.astype methods to mask array 
# and converting it to float64 
out_arr = mask_arr.astype('float64') 
print ("Output typecasted array:", out_arr) 
  
# printing the data type of typecasted masked aaray 
print(out_arr.dtype) 
輸出:
Input array: [ 1  2  3 -1  5]
Masked array: [1 2 -- -1 5]
int32
Output typecasted array: [1.0 2.0 -- -1.0 5.0]
float64

代碼2:

# Python program explaining 
# numpy.MaskedArray.astype() 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([10.1, 20.2, 30.3, 40.4, 50.5], dtype ='float64') 
print ("Input array:", in_arr) 
  
# Now we are creating a masked array by making  
# first and third entry as invalid.  
mask_arr = ma.masked_array(in_arr, mask =[1, 0, 1, 0, 0]) 
print ("Masked array:", mask_arr) 
  
# printing the data type of masked aaray 
print(mask_arr.dtype)  
  
# applying MaskedArray.astype methods to mask array 
# and converting it to int32 
out_arr = mask_arr.astype('int32') 
print ("Output typecasted array:", out_arr) 
  
# printing the data type of typecasted masked aaray 
print(out_arr.dtype) 
輸出:
Input array: [10.1 20.2 30.3 40.4 50.5]
Masked array: [-- 20.2 -- 40.4 50.5]
float64
Output typecasted array: [-- 20 -- 40 50]
int32


相關用法


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