This question already has an answer here:
这个问题在这里已有答案:
- Index n dimensional array with (n-1) d array 2 answers
索引n维数组与(n-1)d数组2答案
It is hard to find a clear title but an example will put it clearly. For example, my inputs are:
很难找到明确的标题,但一个例子会清楚地说明。例如,我的输入是:
c = np.full((4, 3, 2), 5)
c[:,:,1] *= 2
ix = np.random.randint(0, 2, (4, 3))
if ix
is:
如果ix是:
array([[1, 0, 1],
[0, 0, 1],
[0, 0, 1],
[1, 1, 0]])
if want as a result:
如果想要结果:
array([[10, 5, 10],
[ 5, 5, 10],
[ 5, 5, 10],
[10, 10, 5]])
My c array can be of arbitrary dimensions, as well a the dimension I want to sample in.
我的c数组可以是任意尺寸,也是我想要采样的尺寸。
It sounds like interpolation, but I'm reluctant to construct a be array of indices each time I want to apply this. Is there a way of doing this using some kind of indexing on numpy arrays ? Or do I have to use some interpolation methods... Speed and memory are a concern here because I have to do this many times, and the arrays can be really large.
这听起来像插值,但每次我想应用它时,我都不愿意构造一个索引数组。有没有办法在numpy数组上使用某种索引来做到这一点?或者我必须使用一些插值方法...速度和内存是一个问题,因为我必须多次这样做,并且数组可能非常大。
Thanks for any insight !
感谢您的任何见解!
1 个解决方案
#1
3
Create the x, y indices with numpy.ogrid
, and then use advanced indexing:
使用numpy.ogrid创建x,y索引,然后使用高级索引:
idx, idy = np.ogrid[:c.shape[0], :c.shape[1]]
c[idx, idy, ix]
#array([[10, 5, 10],
# [ 5, 5, 10],
# [ 5, 5, 10],
# [10, 10, 5]])
#1
3
Create the x, y indices with numpy.ogrid
, and then use advanced indexing:
使用numpy.ogrid创建x,y索引,然后使用高级索引:
idx, idy = np.ogrid[:c.shape[0], :c.shape[1]]
c[idx, idy, ix]
#array([[10, 5, 10],
# [ 5, 5, 10],
# [ 5, 5, 10],
# [10, 10, 5]])