If you look at the numpy (python) source code, you will find the trick they use to write functions that work on a particular axis is to use np.swapaxes to put the target axis at axis = 0 . Then they write code that runs on 0-axis , and then use np.swapaxes again to return 0-axis to its original position.
You can do it like this:
import numpy as np def rev(a, axis = -1): a = np.asarray(a).swapaxes(axis, 0) a = a[::-1,...] a = a.swapaxes(0, axis) return a a = np.arange(24).reshape(2,3,4) print(rev(a, axis = 2))
gives
[[[ 3 2 1 0] [ 7 6 5 4] [11 10 9 8]] [[15 14 13 12] [19 18 17 16] [23 22 21 20]]]
unutbu
source share