1

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

mrtpk
  • 1,398
  • 4
  • 18
  • 38

2 Answers2

1

You can simply use arr as an indexing array for mapping:

mapping[arr]

the output is

[ 0 10 30 55 55 66 70 90 80 90 30 20 40 66]

You can read on the official SciPy documentation about the indexing arrays. Example from the documentation:

>>> x = np.arange(10,1,-1)
>>> x
array([10,  9,  8,  7,  6,  5,  4,  3,  2])
>>> x[np.array([3, 3, 1, 8])]
array([7, 7, 9, 2])

The values of the indexing array are used as an index for the source array.

This is also possible with multidimensional arrays:


>>> x = array([[ 0,  1,  2],
...            [ 3,  4,  5],
...            [ 6,  7,  8],
...            [ 9, 10, 11]])
>>> rows = np.array([[0, 0],
...                  [3, 3]], dtype=np.intp)
>>> columns = np.array([[0, 2],
...                     [0, 2]], dtype=np.intp)
>>> x[rows, columns]
array([[ 0,  2],
       [ 9, 11]])
Albo
  • 1,584
  • 9
  • 27
1

Just use mapping[arr] to access the correct element in the new Numpy array:

>>> 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])
>>> print(mapping[arr])
array([ 0, 10, 30, 55, 55, 66, 70, 90, 80, 90, 30, 20, 40, 66])

If you want it as a list:

>>> print(list(mapping[arr]))
[0, 10, 30, 55, 55, 66, 70, 90, 80, 90, 30, 20, 40, 66]
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79