Issue
How do I reverse a NumPy array efficiently? I am currently taking a reversed view of it:
reversed_arr = arr[::-1]
Solution
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.
Answered By - steveha
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.