Reverse an arbitrary dimension in an ndarray

后端 未结 3 1172
慢半拍i
慢半拍i 2021-02-20 04:28

I\'m working with an n-dimensional array, and I\'d like a way to reverse a numbered dimension. So rather than

rev = a[:,:,::-1]

I\'d like to be

3条回答
  •  野性不改
    2021-02-20 04:41

    Turns out this can be done with slice, for which : is shorthand in some contexts. The trick is to build the index object as a tuple of slices:

    import numpy as np
    
    def reverse(a, axis=0): 
        idx = [slice(None)]*len(a.shape)
        idx[axis] = slice(None, None, -1)
        return a[idx]
    
    a = np.arange(24).reshape(2,3,4)
    print reverse(a, axis=2)
    

    With Ellipsis this can be collapsed into a one-liner:

    a[[slice(None)]*axis + [slice(None, None, -1)] + [Ellipsis]]
    

提交回复
热议问题