Home > Back-end >  How to remap list of values from an array to another list of values in NumPy?
How to remap list of values from an array to another list of values in NumPy?

Time:06-03

Let's say we have initial array:

test_array = np.array([1, 4, 2, 5, 7, 4, 2, 5, 6, 7, 7, 2, 5])

What is the best way to remap elements in this array by using two other arrays, one that represents elements we want to replace and second one which represents new values which replace them:

map_from = np.array([2, 4, 5])
map_to = np.array([9, 0, 3])

So the results should be:

remaped_array = [1, 0, 9, 3, 7, 0, 9, 3, 6, 7, 7, 9, 3]

CodePudding user response:

There might be a more succinct way of doing this, but this should work by using a mask.

mask = test_array[:,None] == map_from
val = map_to[mask.argmax(1)]
np.where(mask.any(1), val, test_array)

output:

array([1, 0, 9, 3, 7, 0, 9, 3, 6, 7, 7, 9, 3])

CodePudding user response:

If your original array contains only positive integers and their maximum values are not very large, it is easiest to use a mapped array:

>>> a = np.array([1, 4, 2, 5, 7, 4, 2, 5, 6, 7, 7, 2, 5])
>>> mapping = np.arange(a.max()   1)
>>> map_from = np.array([2, 4, 5])
>>> map_to = np.array([9, 0, 3])
>>> mapping[map_from] = map_to
>>> mapping[a]
array([1, 0, 9, 3, 7, 0, 9, 3, 6, 7, 7, 9, 3])

Here is another general method:

>>> vals, inv = np.unique(a, return_inverse=True)
>>> vals[np.searchsorted(vals, map_from)] = map_to
>>> vals[inv]
array([1, 0, 9, 3, 7, 0, 9, 3, 6, 7, 7, 9, 3])
  • Related