将切片组合成多维切片以进行numpy数组切片

时间:2014-04-08 18:34:51

标签: python numpy

如果我在每个维度上定义了两个切片对象,是否可以将它们组合起来以获得可用于切割numpy数组的多维切片对象?

mat = np.zeros((10,10), dtype=np.uint8)
s1 = slice(0,5)
s2 = slice(0,5)
mat[s1,s2]  # I want to achieve this effect with one slice object    
slice2d = slice(s1, s2)  # does not throw an error
mat[slice2d]  # but this does not work

1 个答案:

答案 0 :(得分:1)

正如@unutbu指出的那样,多维切片实际上是tuplelistslice个对象,然后:

slice2d = (s1, s2)
mat[slice2d]

会奏效。同样,您可以将其扩展为3-D,...,N-D阵列:

slice3d = (s1, s2, s3)
...
sliceNd = (s1, s3, s3, ..., sN)