如何在没有for循环的情况下使用变量start和end索引切片numpy数组?

e4yzc0pl  于 2024-01-08  发布在  其他
关注(0)|答案(1)|浏览(132)

我们可以在numpy中做如下切片:

  1. a = np.random.randn(10)
  2. b = a[1: 3] #slice with start=1, end=3

字符串
现在我有了一个开始元组和结束元组,我可以用for循环得到这些切片:

  1. a = np.random.randn(10)
  2. starts = (1, 2)
  3. ends = (3,4)
  4. all_slices = list()
  5. for s, e in zip(starts, ends):
  6. all_slices.append( a[s:e])
  7. all_slices = np.stack(all_slices, axis=0) # shape (2,2)


我可以确保每个切片范围都是相同的:ends[i] - starts[i] = M。假设len(starts)=len(ends)=N,我可以在numpy中得到一个没有for循环的形状为(N,M)的数组吗?

snz8szmq

snz8szmq1#

linspace接受数组输入,因此可以生成索引数组

  1. In [103]: idx=np.linspace(starts,ends,num=2,dtype=int,endpoint=False).T
  2. In [104]: idx
  3. Out[104]:
  4. array([[1, 2],
  5. [2, 3]])

字符串
我不得不将参数调整为整数值,并跳过结束点(默认为linspace)。

  1. In [105]: a[idx]
  2. Out[105]:
  3. array([[1, 2],
  4. [2, 3]])


也许有一种更简单的方法来制作索引数组:

  1. In [106]: idx = np.array(starts)[:,None]+np.arange(2)
  2. In [107]: idx
  3. Out[107]:
  4. array([[1, 2],
  5. [2, 3]])

展开查看全部

相关问题