Python Numpy MaskedArray.astype()函数

Python Numpy MaskedArray.astype()函数

在许多情况下,数据集可能是不完整的,或因存在无效数据而受到污染。例如,一个传感器可能未能记录一个数据,或者记录了一个无效的值。numpy.ma模块通过引入掩码数组,为解决这个问题提供了一个方便的方法。掩码数组是可能存在缺失或无效项的数组。
numpy.MaskedArray.astype()函数返回MaskedArray的副本,并将其转换为指定的newtype。

语法: numpy.MaskedArray.astype(newtype)
参数:
newtype :我们要转换被屏蔽数组的类型。
返回 : [MaskedArray] 自身的一个副本,投向输入的newtype。返回的记录形状符合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 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)

输出:

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

Numpy 数组操作