一个对象中的多维数组切片

时间:2017-12-20 11:02:44

标签: python numpy slice

我有一个numpy数组:

arr = numpy.arange(25 * 10 * 20)
arr.resize((25, 10, 20))

我想得到像这样的切片:

arr[3:6, 2:8, 7:9]

这有效:

index = [slice(3, 6), slice(2, 8), slice(7, 9)]
arr[index]

但这并不是:

>>> index = slice([3, 2, 7], [6, 8, 9])
>>> arr[index]
TypeError: slice indices must be integers or None or have an __index__ method

可以由一个slice对象完成吗?或者只有3个list的{​​{1}}才有效?

3 个答案:

答案 0 :(得分:1)

>>> help(slice)
class slice(object)
 |  slice(stop)
 |  slice(start, stop[, step])

所以我们使用切片(开始,停止,步骤)

>>> import numpy as np
>>> x = np.arange(10)

## ERROR

>>> i=slice([1,3])
>>> x[i]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: slice indices must be integers or None or have an __index__ method

## OK

>>> i = slice(3,7,2)
>>> print(x)
[0 1 2 3 4 5 6 7 8 9]
>>> print(i)
slice(3, 7, 2)
>>> print(x[i])
[3 5]

多维度:

>>> x = np.arange(12).reshape(3,4)
>>> x
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
>>> i = slice(0,3,1)
>>> i
slice(0, 2, 1)
>>> x[i,i]
array([[0, 1],
       [4, 5]])

答案 1 :(得分:1)

您可以创建切片列表,压缩两个索引列表:

>>> slices = [slice(*i) for i in zip([3,2,7], [6,8,9])]
>>> arr[slices]
array([[[ 647,  648],
    [ 667,  668],
    [ 687,  688],
    [ 707,  708],
    [ 727,  728],
    [ 747,  748]],

   [[ 847,  848],
    [ 867,  868],
    [ 887,  888],
    [ 907,  908],
    [ 927,  928],
    [ 947,  948]],

   [[1047, 1048],
    [1067, 1068],
    [1087, 1088],
    [1107, 1108],
    [1127, 1128],
    [1147, 1148]]])

选中numpy.array_equal

>>> numpy.array_equal(arr[slices], arr[3:6,2:8,7:9])
True

答案 2 :(得分:0)

您可以使用numpy.ogrid

  a[ogrid[3:6, 2:8, 7:9]]

选择你阻止。