将掩码数组的元素复制到标准 Python 标量并返回它


要将数组的元素复制到标准 Python 标量并返回它,请在 Numpy 中使用 **ma.MaskedArray.item()** 方法。

*args 参数,如果

  • 无 - 在这种情况下,该方法仅适用于只有一个元素的数组 (a.size == 1),该元素被复制到标准 Python 标量对象中并返回。

  • int_type - 此参数被解释为数组中的平面索引,指定要复制和返回的元素。

  • int_type 元组 - 功能与单个 int_type 参数相同,只是该参数被解释为数组中的 nd 索引。

步骤

首先,导入所需的库 -

import numpy as np
import numpy.ma as ma

使用 numpy.array() 方法创建具有 int 元素的数组 -

arr = np.array([[55, 85, 59, 77], [67, 33, 39, 57], [29, 88, 51, 37], [56, 45, 99, 85]])
print("Array...
", arr) print("
Array type...
", arr.dtype)

获取数组的维度 -

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

创建一个掩码数组并将其中的某些元素标记为无效 -

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

要将数组的元素复制到标准 Python 标量并返回它,请在 Numpy 中使用 ma.MaskedArray.item() 方法 -

print("
Result...
",maskArr.item(7))

示例

Open Compiler
# Python ma.MaskedArray - Copy an element of an array to a standard Python scalar and return it import numpy as np import numpy.ma as ma # Create an array with int elements using the numpy.array() method arr = np.array([[55, 85, 59, 77], [67, 33, 39, 57], [29, 88, 51, 37], [56, 45, 99, 85]]) 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 =[[1, 1, 0, 0], [ 0, 0, 1, 0], [0, 0, 0, 1], [0, 1, 0, 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 copy an element of an array to a standard Python scalar and return it, use the ma.MaskedArray.item() method in Numpy print("Result...",maskArr.item(7))

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

输出

Array...
[[55 85 59 77]
[67 33 39 57]
[29 88 51 37]
[56 45 99 85]]

Array type...
int64

Array Dimensions...
2

Our Masked Array
[[-- -- 59 77]
[67 33 -- 57]
[29 88 51 --]
[56 -- 99 85]]

Our Masked Array type...
int64

Our Masked Array Dimensions...
2

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

Elements in the Masked Array...
16

Result...
57

更新于: 2022年2月2日

137 次浏览

开启你的 职业生涯

通过完成课程获得认证

立即开始
广告