Home > Software design >  Python indexing in multidimentional array
Python indexing in multidimentional array

Time:04-08

I have a 4D numpy array letterOrder (shaped as 2 x 3 x 5 x 4) and I wanted to use each cell as coordinates to find values in a matrix ov.

letterOrder = np.array(
    [[[[4, -1, -1, 2],
     [-1, -1, -1, -1],
     [-1, -1, -1, -1],
     [-1, -1, -1, -1],
     [3, -1, -1, -1]],

    [[4, -1, -1, -1],
     [-1, -1, -1, -1],
     [-1, -1, -1, -1],
     [4, -1, -1, -1],
     [-1, -1, -1, -1]],

    [[-1, -1, -1, -1],
     [-1, -1, -1, -1],
     [-1, -1, -1, -1],
     [-1, -1, -1, -1],
     [-1, -1, -1, -1]]],
    
   [[[-1, -1, -1, -1],
     [-1, -1, -1, -1],
     [3, -1, -1, -1],
     [2, -1, -1, -1],
     [-1, -1, -1, -1]],

    [[4, -1, -1, -1],
     [4, -1, -1, -1],
     [-1, -1, -1, -1],
     [-1, -1, -1, -1],
     [-1, -1, -1, -1]],


    [[0, -1, -1, -1],
     [4, -1, -1, -1],
     [-1, -1, -1, -1],
     [-1, -1, -1, -1],
     [-1, -1, -1, -1]]]], dtype = int)

nData = letterOrder.shape[0]
LL = letterOrder.shape[1]
maxLength = letterOrder.shape[2]
maxCount = letterOrder.shape[3]

ov = np.array(
    [[0.603, 0.235, 0.104, 0.034, 0.008],
     [0.193, 0.334, 0.22 , 0.108, 0.037],
     [0.005, 0.235, 0.283, 0.215, 0.11 ],
     [0.   , 0.082, 0.22 , 0.27 , 0.212],
     [0.   , 0.014, 0.104, 0.215, 0.265],
     [0.   , 0.   , 0.   , 0.   , 0.   ]])  # shaped as (maxLength   1, maxLength)

sims = np.zeros((nData, LL, maxLength))

for i in np.arange(maxCount):
    sims  = ov[letterOrder[:,:,np.arange(maxLength),i], np.arange(maxLength)]

I tried to calculate "sims" without having to loop through each dimension and managed to reduce them down to a single for loop. I was wondering if there is a way for me to calculate "sims" all at once without any for loops?

CodePudding user response:

You can try this:

sims = ov[letterOrder, np.arange(maxLength).reshape(-1, 1)].sum(-1)
  • Related