numpy中的花式索引

dbf7pr2w  于 2022-12-18  发布在  其他
关注(0)|答案(1)|浏览(141)

我基本上是在尝试这样做,但没有for循环...我尝试使用np.put_along_axis,但它要求times的维数为10(与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]
dgtucam1

dgtucam11#

一种方法是使用np.add.at,首先准备索引(如下所示):

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)

产出

[[[  0.   0.   0.   0.   0.   0.   0.   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.]]]

相关问题