python - Numpy - 如何根据条件(或匹配模式)替换元素

标签 python arrays numpy

我有一个 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/

相关文章:

python - 堆积柱

python - 在 Django PostgreSQL 中排序太慢

ios - 排序数组给我错误

python - matplotlib 将数组转换为参数图

numpy 元素外积

Python - 在跨模块共享变量时,字典类型是否不同(参见示例)?

python - 当 .where() 无法将数据转换回原始类型时该怎么办

javascript - Lodash 过滤嵌套对象

javascript - 在 console.log 中打印函数的输出

python - 在python中从一维数组和 bool 数组创建一个二维数组