將輸入轉換為至少具有一維的 NumPy 陣列


要將輸入轉換為至少具有一維的陣列,請在 Python NumPy 中使用 **ma.atleast_1d()** 方法。標量輸入將轉換為一維陣列,而更高維度的輸入將保留。它返回一個數組或陣列列表,每個陣列的 a.ndim >= 1。僅在必要時進行復制。該函式應用於 _data 和 _mask(如果有)。

掩碼陣列是標準 numpy.ndarray 和掩碼的組合。掩碼要麼是 nomask,表示關聯陣列的任何值均無效,要麼是布林值的陣列,用於確定關聯陣列的每個元素的值是否有效。

步驟

首先,匯入所需的庫 -

import numpy as np
import numpy.ma as ma

使用 numpy.array() 方法建立一個包含整數元素的陣列 -

arr = np.array([65, 68, 81])
print("Array...
", arr) print("
Array type...
", arr.dtype)

獲取陣列的維度 -

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

建立一個掩碼陣列,並將其中一些標記為無效 -

maskArr = ma.masked_array(arr, mask =[[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)

使用 ma.atleast_1d() 方法將輸入轉換為至少具有一維的陣列 -

print("
Result...
",np.atleast_1d(1, maskArr))

示例

# Python ma.MaskedArray - Convert inputs to arrays with at least one dimension

import numpy as np
import numpy.ma as ma

# Create an array with int elements using the numpy.array() method
arr = np.array([65, 68, 81])
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, 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 convert inputs to arrays with at least one dimension, use the ma.atleast_1d() method in Python Numpy print("
Result...
",np.atleast_1d(1, maskArr))

輸出

Array...
[65 68 81]

Array type...
int64

Array Dimensions...
1

Our Masked Array
[65 -- 81]

Our Masked Array type...
int64

Our Masked Array Dimensions...
1

Our Masked Array Shape...
(3,)

Elements in the Masked Array...
3

Result...
[array([1]), masked_array(data=[65, --, 81],
   mask=[False, True, False],
fill_value=999999)]

更新於: 2022年2月3日

214 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告