1
 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]
asked Sep 4, 2018 at 18:35
4
  • Can you show the loopy solution just so that we understand the problem better and also use it verify? Commented Sep 4, 2018 at 18:43
  • Could you add your for-loop solution to your post? That would make it more clear what end result exactly you're looking to achieve. Commented Sep 4, 2018 at 18:43
  • thanks, added the for loop based soln Commented Sep 4, 2018 at 18:56
  • updated it again to correct a typo Commented Sep 4, 2018 at 19:07

1 Answer 1

2

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)
answered Sep 4, 2018 at 19:10

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.