將 NumPy 中的掩碼陣列元素轉換為 int 型別


若要將掩碼陣列轉換為 int 型別,請使用 Numpy 中的 **ma.MaskedArray.__int__()** 方法。掩碼可以是不掩碼(指示關聯陣列的任何值都無效),或者是一個布林陣列,該陣列確定關聯陣列的每個元素的值是否有效。

步驟

首先,匯入所需的庫 −

import numpy as np
import numpy.ma as ma

使用 numpy.array() 方法建立一個數組 −

arr = np.array([14.76])
print("Array...", arr)
print("
Array type...", arr.dtype)

獲取陣列的維數 −

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

建立一個掩碼陣列 −

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

獲取掩碼陣列的維數 −

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

將掩碼陣列轉換為 int 型別,請使用 Numpy 中的 ma.MaskedArray.__int__() 方法 −

print("
Result Converted to int type...
",maskArr.__int__())

示例

import numpy as np
import numpy.ma as ma

# Create an array with using the numpy.array() method
arr = np.array([14.76])
print("Array...", arr)
print("
Array type...", arr.dtype) # Get the dimensions of the Array print("
Array Dimensions...",arr.ndim) # Create a masked array maskArr = ma.masked_array(arr, mask =[False]) 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) # To convert masked array to int type, use the ma.MaskedArray.__int__() method in Numpy print("
Result Converted to int type...
",maskArr.__int__())

輸出

Array... [14.76]

Array type... float64

Array Dimensions... 1

Our Masked Array
[14.76]

Our Masked Array type...
float64

Our Masked Array Dimensions...
1

Result Converted to int type...
14

更新時間: 2022 年 2 月 4 日

721 次瀏覽

開啟你的職業生涯

完成課程可獲得認證

開始學習
廣告
© . All rights reserved.