How can I replace all values in a 2D (or 3D) np.array x
with a two-column (key + value to replace) lookup table (another np.array) lookup
?
x = np.array([[0., 1., 5., 2.],
[5., 1., 3., 5.],
[4., 1., 1., 2.],
[0., 1., 3., 2.],
[2., 4., 1., 0.]])
x
may also be 3D and the shape is more or less arbitrary.
lookup = np.array([[0, 1.2],
[1, 3.4],
[2, 0.1],
[3, 2.1],
[4, 5.4],
[5, 2.2]])
Result:
>>> x
array([[1.2, 3.4, 2.2, 0.1],
[2.2, 3.4, 2. , 2.2],
[5.4, 3.4, 3.4, 0.1],
[1.2, 3.4, 2. , 0.1],
[0.1, 5.4, 3.4, 1.2]])
Bonus: Normally all values in x
are represented in the first column of lookup
. How to best handle values in x
that are not represented in lookup
, e.g. by ignoring them from being replaced or by setting them to nan.
A somewhat inefficient approach so far (only working for 2D but may easily be adopted to 3D): Iterate through all elements in x
and compare it with the keys in lookup
.
def replaceByLookup(x, lookup):
for i in range(x.shape[0]):
for j in range(x.shape[1]):
for k in range(lookup.shape[0]):
if x[i,j] == lookup[k,0]:
x[i,j] = lookup[k,1]
break
I am looking for a more efficient and maybe simpler solution. I wonder if there isn't a vectorized solution within numpy. It would also be totally ok if the function does not work by reference but return a new array with the replaced values.