Most efficient way to reverse a numpy array
Because this seems to not be marked as answered yet... The Answer of Thomas Arildsen should be the proper one: just use
np.flipud(your_array)
if it is a 1d array (column array).
With matrizes do
fliplr(matrix)
if you want to reverse rows and flipud(matrix)
if you want to flip columns. No need for making your 1d column array a 2dimensional row array (matrix with one None layer) and then flipping it.
reversed_arr = arr[::-1]
gives a reversed view into the original array arr
. Any changes made to the original array arr
will also be immediately visible in reversed_arr
. The underlying data buffers for arr
and reversed_arr
are shared, so creating this view is always instantaneous, and does not require any additional memory allocation or copying for the array contents.
See also, this discussion on NumPy views: How do I create a view onto a NumPy array?
Possible solutions to performance problems regarding views
Are you re-creating the view more often than you need to? You should be able to do something like this:
arr = np.array(some_sequence)
reversed_arr = arr[::-1]
do_something(arr)
look_at(reversed_arr)
do_something_else(arr)
look_at(reversed_arr)
I'm not a numpy expert, but this seems like it would be the fastest way to do things in numpy. If this is what you are already doing, I don't think you can improve on it.
a[::-1]
only creates a view, so it's a constant-time operation (and as such doesn't take longer as the array grows). If you need the array to be contiguous (for example because you're performing many vector operations with it), ascontiguousarray
is about as fast as flipud
/fliplr
:
Code to generate the plot:
import numpy
import perfplot
perfplot.show(
setup=lambda n: numpy.random.randint(0, 1000, n),
kernels=[
lambda a: a[::-1],
lambda a: numpy.ascontiguousarray(a[::-1]),
lambda a: numpy.fliplr([a])[0],
],
labels=["a[::-1]", "ascontiguousarray(a[::-1])", "fliplr"],
n_range=[2 ** k for k in range(25)],
xlabel="len(a)",
)