3 回答
TA贡献1886条经验 获得超2个赞
您可以使用broadcasting:
a = np.arange(24).reshape(4,6)
thresh = np.array([3, 7, 9, 11, 13, 15])
a > thresh[None,:]
输出:
array([[False, False, False, False, False, False],
[ True, False, False, False, False, False],
[ True, True, True, True, True, True],
[ True, True, True, True, True, True]])
TA贡献1876条经验 获得超5个赞
这里
m
是原始矩阵thresh_vals
是阈值列表(np 数组)rep_vals
是要填充 m < thresh_vals 的相应值的列表
通过以下方式设置阈值和替换值:
m = np.random.rand(4,4)
thresh_vals = np.array([0.25, 0.5, 0.75, 1.0])
m_thresh = np.repeat(thresh_vals.reshape(1,4), 4, axis=0)
rep_vals = np.array([0, 0.1, 0.01, 0.001])
m_rep = np.repeat(rep_vals.reshape(1,4), 4, axis=0)
mask = m < thresh_vals
m[mask] = m_rep[mask]
# m:
[[0.85129154 0.76109774 0.20486053 0.07527921]
[0.97887779 0.70202094 0.11273641 0.98444799]
[0.50364255 0.05257619 0.58271136 0.41479196]
[0.39269314 0.01727273 0.81580523 0.93713313]]
# m after threshold applied, filled with `rep_vals`:
[[0.85129154 0.76109774 0.01 0.001 ]
[0.97887779 0.70202094 0.01 0.001 ]
[0.50364255 0.1 0.01 0.001 ]
[0.39269314 0.1 0.81580523 0.001 ]]
TA贡献1828条经验 获得超13个赞
只需直接将您的矩阵与阈值数组进行比较
如果 x 是 [n,m] numpy 数组并且 t 是 [m,] numpy 数组
x > t
返回一个布尔[n,m]数组,检查x中的每一列是否大于t中相应的阈值
例子:
import numpy as np
v = np.array([
[0,1,2],
[1,2,3],
[2,3,4]])
t = np.array([1,2,3])
v >= t
>> array([[False, False, False],
[ True, True, True],
[ True, True, True]])
添加回答
举报