![]() |
VOOZH | about |
Reversing a NumPy array means changing order of elements so that first element becomes the last and the last becomes the first. This is a common operation when processing data for analysis or visualization.
Let's see how we can reverse a NumPy array. The following methods are commonly used:
The numpy.flip() function reverses the order of array elements along the specified axis. It preserves shape of the array and works efficiently for both 1D and multi-dimensional arrays.
Example: Reverse a 1D array using numpy.flip()
[5 4 6 3 2 1]
Explanation: np.flip(arr) reverses the order of all elements in the array and result is stored in rev as [5, 4, 6, 3, 2, 1].
Slicing with [::-1] is a Pythonic way to reverse arrays. It creates a copy of the array in reversed order. While simple and readable, it may use slightly more memory since it creates a copy.
Example: Reverse a 1D array using slicing
[5 4 6 3 2 1]
Explanation: arr[::-1] reads the array from the last element to the first using the step -1. A new array is created in memory with the elements in reversed order and rev now holds [5, 4, 6, 3, 2, 1].
The numpy.flipud() function flips an array vertically (up-down). For 1D arrays, it behaves like numpy.flip(). For 2D arrays, it reverses rows. It is slightly less general than numpy.flip().
Example: Reverse a 1D array using numpy.flipud()
[5 4 6 3 2 1]
Explanation: np.flipud(arr) flips the array along the vertical axis (up-down). For 1D arrays, this is equivalent to reversing the array and resulting array [5, 4, 6, 3, 2, 1] is stored in rev.