0

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]

2 Answers 2

1

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])
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect. I understand that mask can be quite large and sparse if we use larger arrays, but I don't mind. This solves it. Thanks!
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.