Suppose we have an array of indices of another numpy array:
import numpy as np
a = np.array([0, 3, 1])
b = np.array([0, 10, 20, 30, 40, 50, 60, 70])
We can use the array a as index directly:
b[a] # np.array([0, 30, 10])
But what if array a has more than one dimension? For example,
a = np.array([[0, 2], [1, 3], [2, 4]])
# I want to get b[a] = np.array([[0, 20], [10, 30], [20, 40]])
Numpy indexing doesn't work if the number of dimensions of a is greater than 1. We can achieve the desired result by using map
map(lambda x: b[x], a)
However, it is quite slow. For 1-dimensional case, direct indexing is about 10-100 times faster than using map.
Is there a way to do it faster?
b[a]? - hpauljb[a]will work as desired even ifais 2D. What error are you getting? - jakevdp