Please consider the following code:
arr = np.array([0, 1, 3, 5, 5, 6, 7, 9, 8, 9, 3, 2, 4, 6])
mapping = np.array([0, 10, 20, 30, 40, 55, 66, 70, 80, 90])
res = np.zeros_like(arr)
min_val = 0
max_val = 10
for val in range(min_val, max_val):
res[arr == val] = mapping[val]
print(res)
The Numpy array arr can have multiple occurrences of integers from interval [min_val, max_val). mapping array will have mappings for each integer and the size of the mapping array will be max_val. res array is the resultant array.
The for loop replaces multiple occurring elements in arr with the corresponding value in the mapping. For example, 0 value in the arr will be replaced with mapping[0] and 5 in arr with mapping[5].
The result of the above code is as below.
[ 0 10 30 55 55 66 70 90 80 90 30 20 40 66]
Question: How to do this operation using Numpy instead of for loop?
Answer is to use Numpy's fancy indexing
mapping[arr]?