在 Numpy 中对满足条件的数组进行掩码

numpyserver side programmingprogramming更新于 2025/8/15 1:07:17

要对满足条件的数组进行掩码,请使用 Python Numpy 中的 numpy.ma.masked_where() 方法。将要掩码的数组作为掩码数组返回,其中条件为 True。a 或条件的任何掩码值也会在输出中被掩码。

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

步骤

首先,导入所需的库 −

import numpy as np
import numpy.ma as ma

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

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

获取数组的类型−

print("
数组类型...
", arr.dtype)

获取数组的维度 −

print("
数组维度...
",arr.ndim)

获取数组的形状 −

print("
我们的数组形状...
",arr.shape)

获取数组元素的数量 −

print("
数组中元素的数量...
",arr.size)

要屏蔽满足条件的数组,请使用 Python Numpy 中的 numpy.ma.masked_where() 方法。这里,所有大于 60 的元素都将被屏蔽 −

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

示例

import numpy as np
import numpy.ma as ma

# 使用 numpy.array() 方法创建一个包含 int 元素的数组
arr = np.array([[71, 55, 91], [82, 33, 39], [73, 82, 51], [90, 45, 82]])
print("数组...
", arr) # 获取数组的类型 print("
数组类型...
", arr.dtype) # 获取数组的维度 print("
数组维度...
",arr.ndim) # 获取数组的形状 print("
我们的数组形状...
",arr.shape) # 获取数组元素的数量 print("
数组中元素的数量...
",arr.size) # 要屏蔽满足条件的数组,请使用 Python Numpy 中的 numpy.ma.masked_where() 方法 # 这里,所有大于 60 的元素都将被屏蔽 print("
结果...
",np.ma.masked_where(arr > 60, arr))

输出

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

数组类型...
int64

数组维度...
2

我们的数组形状...
(4, 3)

数组中元素的数量...
12

结果...
[[-- 55 --]
[-- 33 39]
[-- -- 51]
[-- 45 --]]

相关文章