How to reverse a numpy array of unknown dimension?

Viewed 453

I'm just learning python, but have decided to do so by recoding and improving some old java based school AI project.

My project involved a mathematical operation that is basically a discrete convolution operation, but without one of the functions time reversed.

So, while in my original java project I just wrote all the code to do the operation myself, since I'm working in python, and it's got great math libraries like numpy and scipy, I figured I could just make use of an existing convolution function like scipy.convolve. However, this would require me to pre-reverse one of the two arrays so that when scipy.convolve runs, and reverses one of the arrays to perform the convolution, it's really un-reversing the array. (I also still don't know how I can be sure to pre-reverse the right one of the two arrays so that the two arrays are still slid past each other both forwards rather than both backwards, but I assume I should ask that as a separate question.)

Unlike my java code, which only handled one dimensional data, I wanted to extend this project to multidimensional data. And so, while I have learned that if I had a numpy array of known dimension, such as a three dimensional array a, I could fully reverse the array (or rather get back a view that is reversed, which is much faster), by

a = a(::-1, ::-1, ::-1)

However, this requires me to have a ::-1 for every dimension. How can I perform this same reversal within a method for an array of arbitrary dimension that has the same result as the above code?

2 Answers

You can use np.flip. From the documentation:

numpy.flip(m, axis=None)

Reverse the order of elements in an array along the given axis.

The shape of the array is preserved, but the elements are reordered.

Note: flip(m) corresponds to m[::-1,::-1,...,::-1] with ::-1 at all positions.

This is a possible solution:

slices = tuple([slice(-1, -n-1, -1) for n in a.shape])
result = a[slices]

extends to arbitrary number of axes. Verification:

a = np.arange(8).reshape(2, 4)
slices = tuple([slice(-1, -n-1, -1) for n in a.shape])
result = a[slices]

yields:

>>> a
array([[0, 1, 2, 3],
       [4, 5, 6, 7]])
>>> result
array([[7, 6, 5, 4],
       [3, 2, 1, 0]])
Related