Slicing a numpy array along a dynamically specified axis

前端 未结 5 1744
不思量自难忘°
不思量自难忘° 2020-11-29 10:54

I would like to dynamically slice a numpy array along a specific axis. Given this:

axis = 2
start = 5
end = 10

I want to achieve the same r

5条回答
  •  春和景丽
    2020-11-29 11:30

    I think one way would be to use slice(None):

    >>> m = np.arange(2*3*5).reshape((2,3,5))
    >>> axis, start, end = 2, 1, 3
    >>> target = m[:, :, 1:3]
    >>> target
    array([[[ 1,  2],
            [ 6,  7],
            [11, 12]],
    
           [[16, 17],
            [21, 22],
            [26, 27]]])
    >>> slc = [slice(None)] * len(m.shape)
    >>> slc[axis] = slice(start, end)
    >>> np.allclose(m[slc], target)
    True
    

    I have a vague feeling I've used a function for this before, but I can't seem to find it now..

提交回复
热议问题