简体   繁体   English

花式索引 numpy

[英]Fancy indexing in 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 ).我基本上是在尝试做这样的事情,但没有 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]

One approach is to use np.add.at , preparing the indices first (as below):一种方法是使用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)

Output 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.]]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM