NumPy中满足条件的数组掩码


要掩盖满足条件的数组,请在Python NumPy中使用**numpy.ma.masked_where()**方法。将要掩盖的数组返回为在condition为True时被掩盖的数组。a或condition的任何掩盖值在输出中也会被掩盖。

condition参数设置掩码条件。当condition测试浮点值的相等性时,请考虑使用masked_values代替。copy参数,如果为True(默认值),则在结果中复制a。如果为False,则就地修改a并返回视图。

步骤

首先,导入所需的库:

import numpy as np
import numpy.ma as ma

使用numpy.array()方法创建一个包含整数元素的数组:

arr = np.array([[71, 55, 91], [82, 33, 39], [73, 82, 51], [90, 45, 82]])
print("Array...
", arr)

获取数组的类型:

print("
Array type...
", arr.dtype)

获取数组的维度:

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

获取数组的形状:

print("
Our Array Shape...
",arr.shape)

获取数组的元素个数:

print("
Number of Elements in the Array...
",arr.size)

要掩盖满足条件的数组,请在Python NumPy中使用numpy.ma.masked_where()方法。这里,所有大于60的元素都将被掩盖:

print("
Result...
",np.ma.masked_where(arr > 60, arr))

示例

import numpy as np
import numpy.ma as ma

# Create an array with int elements using the numpy.array() method
arr = np.array([[71, 55, 91], [82, 33, 39], [73, 82, 51], [90, 45, 82]])
print("Array...
", arr) # Get the type pf array print("
Array type...
", arr.dtype) # Get the dimensions of the Array print("
Array Dimensions...
",arr.ndim) # Get the shape of the Array print("
Our Array Shape...
",arr.shape) # Get the number of elements of the Array print("
Number of Elements in the Array...
",arr.size) # To mask an array where a condition is met, use the numpy.ma.masked_where() method in Python Numpy # Here, all the elements above 60 will get masked print("
Result...
",np.ma.masked_where(arr > 60, arr))

输出

Array...
[[71 55 91]
[82 33 39]
[73 82 51]
[90 45 82]]

Array type...
int64

Array Dimensions...
2

Our Array Shape...
(4, 3)

Number of Elements in the Array...
12

Result...
[[-- 55 --]
[-- 33 39]
[-- -- 51]
[-- 45 --]]

更新于:2022年2月4日

5K+浏览量

开启你的职业生涯

通过完成课程获得认证

开始学习
广告