一次从numpy数组中选择多个切片 [英] Selecting multiple slices from a numpy array at once
问题描述
我正在寻找一种从numpy数组中一次选择多个切片的方法.假设我们有一个1D数据数组,并希望提取其中的三个部分,如下所示:
I'm looking for a way to select multiple slices from a numpy array at once. Say we have a 1D data array and want to extract three portions of it like below:
data_extractions = []
for start_index in range(0, 3):
data_extractions.append(data[start_index: start_index + 5])
随后data_extractions
将是:
data_extractions = [
data[0:5],
data[1:6],
data[2:7]
]
有没有没有for循环的执行上述操作的方法? numpy中的某种索引方案可以让我从一个数组中选择多个切片,然后将它们返回为与多个数组相同的数组,例如在n + 1维数组中?
Is there any way to perform above operation without the for loop? Some sort of indexing scheme in numpy that would let me select multiple slices from an array and return them as that many arrays, say in an n+1 dimensional array?
我想也许我可以复制我的数据,然后从每一行中选择一个范围,但是下面的代码会引发IndexError
I thought maybe I can replicate my data and then select a span from each row, but code below throws an IndexError
replicated_data = np.vstack([data] * 3)
data_extractions = replicated_data[[range(3)], [slice(0, 5), slice(1, 6), slice(2, 7)]
推荐答案
您可以使用索引将所需的行选择为适当的形状. 例如:
You can use the indexes to select the rows you want into the appropriate shape. For example:
data = np.random.normal(size=(100,2,2,2))
# Creating an array of row-indexes
indexes = np.array([np.arange(0,5), np.arange(1,6), np.arange(2,7)])
# data[indexes] will return an element of shape (3,5,2,2,2). Converting
# to list happens along axis 0
data_extractions = list(data[indexes])
np.all(data_extractions[1] == data[1:6])
True
最终比较是与原始数据进行的.
The final comparison is against the original data.
这篇关于一次从numpy数组中选择多个切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!