如何将numpy数组二值化为高于阈值的行中的相应最大值。如果数组行的最大值小于阈值,那么第1列应该等于1。
a=np.array([[ 0.01, 0.3 , 0.6 ],
[ 0.2 , 0.1 , 0.4 ],
[ 0.7 , 0.1 , 0.3 ],
[ 0.2 , 0.3 , 0.5 ],
[ 0.1 , 0.7 , 0.3 ],
[ 0.1 , 0.5 , 0.8 ]])
#required output with thresold row.max>=0.6 else column 1 should be 1
np.array([[ 0.0 , 0.0 , 1.0 ],
[ 0.0 , 1.0 , 0.0 ],
[ 1.0 , 0.0 , 0.0 ],
[ 0.0 , 1.0 , 0.0 ],
[ 0.0 , 1.0 , 0.0 ],
[ 0.0 , 0.0 , 1.0 ]])
答案 0 :(得分:1)
一种解决方案:使用argmax
和高级索引
am = a.argmax(axis=-1)
am[a[np.arange(len(a)), am] < 0.6] = 1
out = np.zeros_like(a)
out[np.arange(len(a)), am] = 1
out
array([[ 0., 0., 1.],
[ 0., 1., 0.],
[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])