# Apply 1D array representing index to element translation over 2D array of index values?

## Question:

I have a 2D array

``````arr = np.array([
[ 1,  2, -1, -1],
[ 0,  1, -1, -1],
[ 3,  5, -1, -1],
[ 7,  8, -1, -1],
[ 6,  7, -1, -1],
[ 9, 11, -1, -1]])
``````

Its elements are related to the indices of some other array. A `-1` value represent "no index". I also have a translation of the elements in `arr` to some other value (indices of a different array) in the form of

``````trans = np.array([[ 0],
[-1],
[ 1],
[-1],
[ 2],
[-1],
[ 3],
[-1],
[ 4],
[-1],
[ 5],
[-1]])
``````

Here the `n`th element of `trans` denotes the mapping of the element values in `arr` to the element value of `trans`. For example, a `8` in `arr` should be translated to a value of `4` (`trans[8]` == `4`).

How can I apply `trans` to translate the values of `arr`?

Desired output

``````np.array([
[-1, 1, -1, -1],
[0, -1, -1, -1],
[-1, -1, -1, -1],
[-1, 4, -1, -1],
[3, -1, -1, -1],
[-1, -1, -1, -1]
])
``````

Just flatten `trans`, and index it with `arr`. Note that this results in the entries that were `-1` in `arr` being translated to the last entry in `trans`. To fix this, you can manually assign `-1` to all entries that were `-1` in `arr`:

``````result = trans.flat[arr]
result[arr == -1] = -1

print(repr(result))
``````

outputs

``````array([[-1.,  1., -1., -1.],
[ 0., -1., -1., -1.],
[-1., -1., -1., -1.],
[-1.,  4., -1., -1.],
[ 3., -1., -1., -1.],
[-1., -1., -1., -1.]])
``````

Note that the result will have the dtype of `trans`.

If you want to avoid doing unnecessary lookups into the last element of `trans` for the `-1` entries in `arr` (as in this answer), you can instead create a copy of `arr` and then use similar indexing to only update the non-`-1` entries:

``````result = arr.copy()

has_index = arr != -1
result[has_index] = trans.flat[arr[has_index]].flat

print(repr(result))
``````

which outputs

``````array([[-1,  1, -1, -1],
[ 0, -1, -1, -1],
[-1, -1, -1, -1],
[-1,  4, -1, -1],
[ 3, -1, -1, -1],
[-1, -1, -1, -1]])
``````

Note that the result will have the dtype of `arr`.

Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.