獲取在 NumPy 中遍歷時每個維度步長的位元組元組


要獲取在遍歷陣列時每個維度步長的位元組元組,請使用 NumPy 中的 **ma.MaskedArray.strides** 屬性。陣列 *a* 中元素 (i[0], i[1], ..., i[n]) 的位元組偏移量為:

offset = sum(np.array(i) * a.strides)

掩碼要麼是 nomask,表示關聯陣列的無任何值無效,要麼是一個布林值陣列,它決定關聯陣列的每個元素的值是否有效。

步驟

首先,匯入所需的庫:

import numpy as np
import numpy.ma as ma

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

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

獲取陣列的維度:

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

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

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

獲取掩碼陣列的 itemsize:

print("
Our Masked Array itemsize...
", maskArr.itemsize)

獲取掩碼陣列的維度:

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.strides 屬性

print("
Strides...
",maskArr.strides)

示例

import numpy as np
import numpy.ma as ma

arr = np.array([[35, 85], [67, 33]])
print("Array...
", arr) print("
Array type...
", arr.dtype) print("
Array itemsize...
", arr.itemsize) # 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], [ 0, 1]]) print("
Our Masked Array
", maskArr) print("
Our Masked Array type...
", maskArr.dtype) # Get the itemsize of the Masked Array print("
Our Masked Array itemsize...
", maskArr.itemsize) # 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 get the Tuple of bytes to step in each dimension when traversing an array, use the ma.MaskedArray.strides attribute in Numpy print("
Strides...
",maskArr.strides)

輸出

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

Array type...
int64

Array itemsize...
8
Array Dimensions...
2

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

Our Masked Array type...
int64

Our Masked Array itemsize...
8

Our Masked Array Dimensions...
2

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

Elements in the Masked Array...
4

Strides...
(16, 8)

更新於:2022年2月22日

95 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

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