【发布时间】:2021-02-22 09:35:34
【问题描述】:
我想通过掩码选择值并通过使用掩码数组更改值。
代码:
import numpy as np
a = np.zeros((2, 2), dtype=(np.uint8, 3))
x = np.arange(4, dtype=int).reshape((2, 2))
mask = np.logical_and(a1 < 3, a1 > 0)
a[mask] = (1, x[mask], 2)
我想要结果:
a[mask]
>> [[1, 1, 2], [1, 2, 2]]
但我得到错误:
ValueError: setting an array element with a sequence.
如果尝试做a[mask] = (1, 2, 2)之类的事情
数组将是
[[[0, 0, 0],
[1, 2, 2]],
[[1, 2, 2],
[0, 0, 0]]]
但我需要使用 x 中的值。 让它看起来像
[[[0, 0, 0],
[1, 1, 3]],
[[1, 2, 3],
[0, 0, 0]]]
我该怎么做?
【问题讨论】:
-
a = np.zeros((2, 2, 3), dtype=np.uint8)是创建a的更清晰的方法。 -
a1是什么?a的副本?x?还是隐藏的东西?
标签: python numpy boolean-indexing