对每列使用不同阈值的 numpy 数组进行阈值化

我正在尝试完全按照这个问题在Python中对R的要求:每列的不同硬阈值也就是说,在$n\times m$ numpy数组上每列应用不同的阈值。

我知道的唯一方法是迭代列,但必须有一种矢量方法来做到这一点(也许使用视图或步幅)?


慕村225694
浏览 150回答 3
3回答

MM们

您可以使用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]])

慕运维8079593

这里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_valsm[mask] = m_rep[mask]# m:[[0.85129154 0.76109774 0.20486053 0.07527921]&nbsp;[0.97887779 0.70202094 0.11273641 0.98444799]&nbsp;[0.50364255 0.05257619 0.58271136 0.41479196]&nbsp;[0.39269314 0.01727273 0.81580523 0.93713313]]&nbsp;# m after threshold applied, filled with `rep_vals`:[[0.85129154 0.76109774 0.01&nbsp; &nbsp; &nbsp; &nbsp;0.001&nbsp; &nbsp; &nbsp;]&nbsp;[0.97887779 0.70202094 0.01&nbsp; &nbsp; &nbsp; &nbsp;0.001&nbsp; &nbsp; &nbsp;]&nbsp;[0.50364255 0.1&nbsp; &nbsp; &nbsp; &nbsp; 0.01&nbsp; &nbsp; &nbsp; &nbsp;0.001&nbsp; &nbsp; &nbsp;]&nbsp;[0.39269314 0.1&nbsp; &nbsp; &nbsp; &nbsp; 0.81580523 0.001&nbsp; &nbsp; &nbsp;]]

慕田峪7331174

只需直接将您的矩阵与阈值数组进行比较如果 x 是 [n,m] numpy 数组并且 t 是 [m,] numpy 数组x > t返回一个布尔[n,m]数组,检查x中的每一列是否大于t中相应的阈值例子:import numpy as npv = np.array([[0,1,2],[1,2,3],[2,3,4]])t = np.array([1,2,3])v >= t>> array([[False, False, False],&nbsp; &nbsp;[ True,&nbsp; True,&nbsp; True],&nbsp; &nbsp;[ True,&nbsp; True,&nbsp; True]])
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python