user308827
user308827

Reputation: 21981

Fill in numpy array upto position based on another array

    import numpy as np
    arr_keys = np.array(np.mat('2 3 1 0; 3 3 3 1'))
    arr_rand1 = np.random.rand(2, 4)
    arr_rand2 = np.random.rand(2, 4)

    arr_final = np.zeros((5, 2, 4))

I want to create a numpy array called arr_final of shape (100, 2, 4) where 100 can be thought to correspond to time and 2, 4 are number of rows and columns respectively To fill arr_final, I want to use the following logic:

  1. For each grid cell in arr_final, look up value in corresponding position in arr_keys, lets call it val_alpha

  2. Fill arr_final using values from arr_rand1 upto the val_alpha position, and using values from arr_rand2 after that

This can be done using a for loop but is there a more pythonic solution?

--EDIT:

Here's the for loop soln:

for (i, j, k), value in np.ndenumerate(arr_final):
    val_alpha = arr_keys[j][k]
    arr_final[:val_alpha, j, k] = arr_rand1[j, k]
    arr_final[val_alpha:, j, k] = arr_rand2[j, k]

Upvotes: 1

Views: 256

Answers (1)

Divakar
Divakar

Reputation: 221604

We could make use of broadcasting and boolean-indexing/masking -

L = 5 # length of output array
mask = arr_keys > np.arange(L)[:,None,None]
arr_final_out = np.where(mask,arr_rand1,arr_rand2)

Upvotes: 2

Related Questions