返回NumPy中强制转换为指定类型掩码数组的副本


要返回数组的副本并强制转换为指定类型,请在NumPy中使用**ma.MaskedArray.astype()**方法。参数是要将数组强制转换到的数据类型。另一个参数order控制结果的内存布局顺序。“C”表示C顺序,“F”表示Fortran顺序,“A”表示如果所有数组都是Fortran连续的则为“F”顺序,否则为“C”顺序,“K”表示尽可能接近数组元素在内存中出现的顺序。默认为“K”。

简单数据类型和结构化数据类型之间的强制转换仅适用于“不安全”强制转换。

允许强制转换到多个字段,但不允许从多个字段强制转换。

返回ndarray,除非copy为False且满足返回输入数组的其他条件,arr_t是与输入数组形状相同的新数组,dtype和order由dtype和*order*给出。

步骤

首先,导入所需的库:

import numpy as np
import numpy.ma as ma

使用numpy.array()方法创建一个包含整数元素的数组:

arr = np.array([[35, 85, 45], [67, 33, 59]])
print("Array...
", arr) print("
Array type...
", arr.dtype)

获取数组的维度:

print("Array Dimensions...
",arr.ndim)

创建一个掩码数组并将其中一些标记为无效:

maskArr = ma.masked_array(arr, mask =[[0, 0, 1], [ 0, 1, 0]])
print("
Our Masked Array
", maskArr) print("
Our Masked Array type...
", maskArr.dtype)

获取掩码数组的维度:

print("
Our Masked Array Dimensions...
",maskArr.ndim)

获取掩码数组的形状:

print("
Our Masked Array Shape...
",maskArr.shape)

获取掩码数组的元素个数:

print("
Elements in the Masked Array...
",maskArr.size)

返回数组的副本,强制转换为指定类型,在NumPy中使用ma.MaskedArray.astype()方法:

print("
Copy of the array cast to float type...
",maskArr.astype(float))

示例

# Python ma.MaskedArray - Copy of the array, cast to a specified type

import numpy as np
import numpy.ma as ma

# Create an array with int elements using the numpy.array() method
arr = np.array([[35, 85, 45], [67, 33, 59]])
print("Array...
", arr) print("
Array type...
", arr.dtype) # Get the dimensions of the Array print("Array Dimensions...
",arr.ndim) # Create a masked array and mask some of them as invalid maskArr = ma.masked_array(arr, mask =[[0, 0, 1], [ 0, 1, 0]]) print("
Our Masked Array
", maskArr) print("
Our Masked Array type...
", maskArr.dtype) # Get the dimensions of the Masked Array print("
Our Masked Array Dimensions...
",maskArr.ndim) # Get the shape of the Masked Array print("
Our Masked Array Shape...
",maskArr.shape) # Get the number of elements of the Masked Array print("
Elements in the Masked Array...
",maskArr.size) # To return the copy of the array, cast to a specified type, use the ma.MaskedArray.astype() method in Numpy # Here, the parameter is the data-type to which the array is cast print("
Copy of the array cast to float type...
",maskArr.astype(float))

输出

Array...
[[35 85 45]
[67 33 59]]

Array type...
int32

Array Dimensions...
2

Our Masked Array
[[35 85 --]
[67 -- 59]]

Our Masked Array type...
int32

Our Masked Array Dimensions...
2

Our Masked Array Shape...
(2, 3)

Elements in the Masked Array...
6

Copy of the array cast to float type...
[[35.0 85.0 --]
[67.0 -- 59.0]]

更新于:2022年2月2日

93 次浏览

开启您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.