一次从 numpy 数组中选择多个切片

新手上路,请多包涵

我正在寻找一种方法来一次从 numpy 数组中选择多个切片。假设我们有一个一维数据数组,想要提取它的三个部分,如下所示:

 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 维数组中?


我想也许我可以复制我的数据,然后从每一行中选择一个跨度,但是下面的代码抛出一个 IndexError

 replicated_data = np.vstack([data] * 3)
data_extractions = replicated_data[[range(3)], [slice(0, 5), slice(1, 6), slice(2, 7)]

原文由 Puchatek 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 854
2 个回答

您可以使用索引来选择您想要的行到适当的形状。例如:

  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

最后的比较是针对原始数据。

原文由 tmrlvi 发布,翻译遵循 CC BY-SA 4.0 许可协议

stride_tricks 可以做到

a = np.arange(10)
b = np.lib.stride_tricks.as_strided(a, (3, 5), 2 * a.strides)
b
# array([[0, 1, 2, 3, 4],
#        [1, 2, 3, 4, 5],
#        [2, 3, 4, 5, 6]])

Please note that b references the same memory as a , in fact multiple times (for example b[0, 1] and b[1, 0] are the same memory address ).因此,在使用新结构之前制作副本是最安全的。

nd 可以用类似的方式完成,例如 2d -> 4d

 a = np.arange(16).reshape(4, 4)
b = np.lib.stride_tricks.as_strided(a, (3,3,2,2), 2*a.strides)
b.reshape(9,2,2) # this forces a copy
# array([[[ 0,  1],
#         [ 4,  5]],

#        [[ 1,  2],
#         [ 5,  6]],

#        [[ 2,  3],
#         [ 6,  7]],

#        [[ 4,  5],
#         [ 8,  9]],

#        [[ 5,  6],
#         [ 9, 10]],

#        [[ 6,  7],
#         [10, 11]],

#        [[ 8,  9],
#         [12, 13]],

#        [[ 9, 10],
#         [13, 14]],

#        [[10, 11],
#         [14, 15]]])

原文由 Paul Panzer 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题