当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。