我有一个 numpy 数组,比如:
>>> a=np.array([[0,1,2],[4,3,6],[9,5,7],[8,9,8]])
>>> a
array([[0, 1, 2],
[4, 3, 6],
[9, 5, 7],
[8, 9, 8]])
我想用它们中的最小值(逐行)替换第二和第三列元素,除非这两个元素之一小于 3。 结果数组应该是:
array([[0, 1, 2],# nothing changes since 1 and 2 are <3
[4, 3, 3], #min(3,6)=3 => 6 changed to 3
[9, 5, 5], #min(5,7)=5 => 7 changed to 5
[8, 8, 8]]) #min(9,8)=8 => 9 changed to 8
我知道我可以使用剪辑,例如 a[:,1:3].clip(2,6,a[:,1:3])
,但是
1) 剪辑将应用于所有元素,包括 <3.
2) 我不知道如何将剪辑的最小值和最大值设置为每行的 2 个相关元素的最小值。
最佳答案
只需使用 >= 运算符首先选择您感兴趣的内容:
b = a[:, 1:3] # select the columns
matching = numpy.all(b >= 3, axis=1) # find rows with all elements matching
b = b[matching, :] # select rows
现在您可以用最小值替换内容,例如:
# find row minimum and convert to a column vector
b[:, :] = b.min(1, keepdims=True)
关于python - Numpy - 如何根据条件(或匹配模式)替换元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23077061/