返回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.