Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to reverse a numpy array

Tags:

python

numpy

Believe it or not, after profiling my current code, the repetitive operation of numpy array reversion ate a giant chunk of the running time. What I have right now is the common view-based method:

reversed_arr = arr[::-1] 

Is there any other way to do it more efficiently, or is it just an illusion from my obsession with unrealistic numpy performance?

like image 500
nye17 Avatar asked Jul 21 '11 04:07

nye17


People also ask

How do I reverse a numpy array?

Using flip() Method The flip() method in the NumPy module reverses the order of a NumPy array and returns the NumPy array object.

How do I reverse a numpy array vertically?

You can flip the image vertically and horizontally by using numpy. flip() , numpy. flipud() , numpy. fliplr() .


1 Answers

When you create reversed_arr you are creating a view into the original array. You can then change the original array, and the view will update to reflect the changes.

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.

P.S. Great discussion of numpy views here:

View onto a numpy array?

like image 60
steveha Avatar answered Oct 16 '22 02:10

steveha