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:
For each grid cell in
arr_final
, look up value in corresponding position inarr_keys
, lets call itval_alpha
Fill
arr_final
using values fromarr_rand1
upto theval_alpha
position, and using values fromarr_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]
-
Can you show the loopy solution just so that we understand the problem better and also use it verify?Divakar– Divakar2018年09月04日 18:43:04 +00:00Commented 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.Xukrao– Xukrao2018年09月04日 18:43:11 +00:00Commented Sep 4, 2018 at 18:43
-
thanks, added the for loop based solnuser308827– user3088272018年09月04日 18:56:36 +00:00Commented Sep 4, 2018 at 18:56
-
updated it again to correct a typouser308827– user3088272018年09月04日 19:07:50 +00:00Commented Sep 4, 2018 at 19:07
1 Answer 1
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)