根据另一个数组中的出现替换二维数组中的元素 [英] Replace elements in 2D array based on occurrence in another array
问题描述
我需要根据元素出现在其他 replacement
数组
I need to replace elements in Numpy 2D arrays based on a condition that the element appears in some other replacement
array
例如:
>>> main = np.random.randint(5, size=(3, 4))
>>> main
array([[1, 2, 4, 2],
[3, 2, 3, 2],
[4, 4, 2, 3]])
>>> repl = [2,3]
>>> main[main in repl] = -1
我想将 repl
中的所有值都更改为-1,所以我希望main为:
I would like to have all values in repl
changed to -1, so I expect main to be:
[[1, -1, 4, -1],
[-1, -1, -1, -1],
[4, 4, -1, -1]]
但是,在尝试使 in
处于替换条件之内时,引发了 ValueError
However a ValueError
is raised while trying to have in
inside the condition of replacement
ValueError:具有多个元素的数组的真值不明确.使用a.any()或a.all()
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
推荐答案
我们可以使用 np.in1d
来创建所有此类事件的展平掩码,并在展平输入中将其设置为 -1
,如下所示-
We can use np.in1d
to create a flattened mask of all such occurrences and set those as -1
in the flattened input, like so -
main.ravel()[np.in1d(main, repl)] = -1
或者,我们可以使用 np.putmask
并因此避免 np.ravel()
以避免显式展平,就像这样-
Alternatively, we can use np.putmask
and thus avoid np.ravel()
to avoid the explicit flattening, like so -
np.putmask(main, np.in1d(main, repl), -1)
这篇关于根据另一个数组中的出现替换二维数组中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!