Home > database >  Fancy indexing in numpy
Fancy indexing in numpy

Time:12-14

I am basically trying to do something like this but without the for-loop... I tried with np.put_along_axis but it requires times to be of dimension 10 (same as last index of src).


import numpy as np

src = np.zeros((5,5,10), dtype=np.float64)

ix = np.array([4, 0, 0])
iy = np.array([1, 3, 4])

times = np.array([1 ,2, 4])
values = np.array([25., 10., -65.])

for i, time in enumerate(times):
    src[ix, iy, time]  = values[i]

CodePudding user response:

One approach is to use np.add.at, preparing the indices first (as below):

r = len(values)
indices = (np.tile(ix, r), np.tile(iy,  r), np.repeat(times, r))
np.add.at(src, indices, np.repeat(values, r))
print(src)

Output

[[[  0.   0.   0.   0.   0.   0.   0.   0.   0.   0.]
  [  0.   0.   0.   0.   0.   0.   0.   0.   0.   0.]
  [  0.   0.   0.   0.   0.   0.   0.   0.   0.   0.]
  [  0.  25.  10.   0. -65.   0.   0.   0.   0.   0.]
  [  0.  25.  10.   0. -65.   0.   0.   0.   0.   0.]]

 [[  0.   0.   0.   0.   0.   0.   0.   0.   0.   0.]
  [  0.   0.   0.   0.   0.   0.   0.   0.   0.   0.]
  [  0.   0.   0.   0.   0.   0.   0.   0.   0.   0.]
  [  0.   0.   0.   0.   0.   0.   0.   0.   0.   0.]
  [  0.   0.   0.   0.   0.   0.   0.   0.   0.   0.]]

 [[  0.   0.   0.   0.   0.   0.   0.   0.   0.   0.]
  [  0.   0.   0.   0.   0.   0.   0.   0.   0.   0.]
  [  0.   0.   0.   0.   0.   0.   0.   0.   0.   0.]
  [  0.   0.   0.   0.   0.   0.   0.   0.   0.   0.]
  [  0.   0.   0.   0.   0.   0.   0.   0.   0.   0.]]

 [[  0.   0.   0.   0.   0.   0.   0.   0.   0.   0.]
  [  0.   0.   0.   0.   0.   0.   0.   0.   0.   0.]
  [  0.   0.   0.   0.   0.   0.   0.   0.   0.   0.]
  [  0.   0.   0.   0.   0.   0.   0.   0.   0.   0.]
  [  0.   0.   0.   0.   0.   0.   0.   0.   0.   0.]]

 [[  0.   0.   0.   0.   0.   0.   0.   0.   0.   0.]
  [  0.  25.  10.   0. -65.   0.   0.   0.   0.   0.]
  [  0.   0.   0.   0.   0.   0.   0.   0.   0.   0.]
  [  0.   0.   0.   0.   0.   0.   0.   0.   0.   0.]
  [  0.   0.   0.   0.   0.   0.   0.   0.   0.   0.]]]
  • Related