Slicing NumPy array given start and end indices for generic dimensions

流过昼夜 提交于 2019-12-02 03:51:27

问题


Given a numpy array x of shape (N_1...N_k) where k is arbitrary, and 2 arrays :

start_indices=[a_1,...,a_k], end_indices=[b_1,...b_k], where `0<=a_i<b_i<=N_i`.

I want to slice x as follows: x[a_1:b_1,...,a_k:b_k].

Lets say :

x is of shape `(1000, 1000, 1000)`
start_indices=[450,0,400]
end_indices=[550,1000,600].

I want the output to be equal x[450:550,0:1000,400:600].

For example I tried to define :

slice_arrays = (np.arange(start_indices[i], end_indices[i]) for i in range(k))

and use

x[slice_arrays]

but it didn't work.


回答1:


You can use slice notation to create an indexing tuple that could be used for the indexing -

indexer = tuple([slice(i,j) for (i,j) in zip(start_indices,end_indices)])
out = x[indexer]

Alternatively, with shorthand np.s_ -

indexer = tuple([np.s_[i:j] for (i,j) in zip(start_indices,end_indices)])

Or with map for a compact one -

indexer = tuple(map(slice,start_indices,end_indices))


来源:https://stackoverflow.com/questions/56236779/slicing-numpy-array-given-start-and-end-indices-for-generic-dimensions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!