0

Let's say I have the following array:

a = np.random.randint(5, size=(2000, 2000, 1))
a = np.repeat(a, 3, axis=2) # Using this method to have a (m,n,3) array with the same values

and the next arrays:

val_old = np.array([[0,  0,   0],  [3,  3,  3]])
val_new = np.array([[12, 125, 13], [78, 78, 0]])

What I want to do is to replace the values from the array a with the values specified in the array val_new. So, all [0,0,0] arrays would become [12,125,13] and all [3,3,3] would become [78, 78, 0].

I can't find an efficient way to do this... I tried to adapt this solution but it's only for 1-d arrays...

Does anyone know a fast way/method to replace these values ?

1
  • Would all three values in each of the row in val_old be the same? Also, are all rows from val_old guaranteed to be in a? And can we use a = np.random.randint(5, size=(2000, 2000, 1)) as the starting point, that is since the repeated version would have the values repeated anyway, so start off with the original "2D" version? Commented Apr 15, 2019 at 18:14

1 Answer 1

1

Assuming you have a "map" for each integer, you can use a (2000, 2000) index on a (5,) array to broadcast to a (2000,2000, 5) array. example:

val_new = np.array([[12, 125, 13], [0,0,0], [1,3,3], [78, 78, 0]])  #0, 1, 2, 3
a = np.random.randint(4,size=(4,5))

val_new[a]  # (4,5,3) shaped array

>>array([[[  0,   0,   0],
    [ 78,  78,   0],
    [ 78,  78,   0],
    [ 12, 125,  13],
    [  0,   0,   0]],
....
   [[ 12, 125,  13],
    [ 12, 125,  13],
    [  0,   0,   0],
    [ 12, 125,  13],
    [  0,   0,   0]]])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.