给定通用维度的开始和结束索引,对NumPy数组进行切片 [英] Slicing NumPy array given start and end indices for generic dimensions
本文介绍了给定通用维度的开始和结束索引,对NumPy数组进行切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出一个形状为(N_1...N_k)
的numpy数组x,其中k是任意的,还有2个数组:
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`.
我想对x进行如下切片:x[a_1:b_1,...,a_k:b_k]
.
I want to slice x as follows: x[a_1:b_1,...,a_k:b_k]
.
让我们说:
x is of shape `(1000, 1000, 1000)`
start_indices=[450,0,400]
end_indices=[550,1000,600].
我希望输出等于x[450:550,0:1000,400:600]
.
例如,我尝试定义:
slice_arrays = (np.arange(start_indices[i], end_indices[i]) for i in range(k))
并使用
x[slice_arrays]
但是没有用.
推荐答案
您可以使用slice
表示法创建可用于索引的索引元组-
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]
或者,用速记 np.s_
-
Alternatively, with shorthand np.s_
-
indexer = tuple([np.s_[i:j] for (i,j) in zip(start_indices,end_indices)])
或与map
组合在一起-
indexer = tuple(map(slice,start_indices,end_indices))
这篇关于给定通用维度的开始和结束索引,对NumPy数组进行切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文