Replace elements in 2D array based on occurrence in another array

徘徊边缘 提交于 2021-02-05 08:09:00

问题


I need to replace elements in Numpy 2D arrays based on a condition that the element appears in some other replacement array

For example:

>>> 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

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]]

However a ValueError is raised while trying to have in inside the condition of replacement

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()


回答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

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)



回答2:


You can make a boolean mask and use it like this:

mask = np.logical_or(main == repl[0], main == repl[1])
main[mask] = -1



回答3:


Not sure if there's any native numpy method for this, but in old fashion python you can do:

import numpy as np

main = np.random.randint(5, size=(3, 4))
repl = [2,3]
for k1, v1 in enumerate(main):
    for k2, v2 in enumerate(v1):
        if(v2 in repl):
            main[k1][k2] = -1
print(main)


来源:https://stackoverflow.com/questions/40828902/replace-elements-in-2d-array-based-on-occurrence-in-another-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!