Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fancy indexing in numpy

Tags:

python

numpy

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]
like image 971
Antoine Collet Avatar asked Feb 04 '26 00:02

Antoine Collet


1 Answers

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.]]]
like image 113
Dani Mesejo Avatar answered Feb 06 '26 12:02

Dani Mesejo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!