📜  Numpy MaskedArray.astype()函数| Python

📅  最后修改于: 2022-05-13 01:55:26.463000             🧑  作者: Mango

Numpy MaskedArray.astype()函数| Python

在许多情况下,数据集可能不完整或因存在无效数据而受到污染。例如,传感器可能无法记录数据,或记录无效值。 numpy.ma 模块通过引入掩码数组提供了解决此问题的便捷方法。掩码数组是可能缺少或无效条目的数组。
numpy.MaskedArray.astype()函数将 MaskedArray 强制转换的副本返回给给定的新类型。

代码#1:

Python3
# 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 array
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 array
print(out_arr.dtype)


Python3
# 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 array
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 array
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:

Python3

# 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 array
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 array
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