How To Reverse An Numpy Array ?
Table Of Contents:
- np.flip( )
- Examples Of ‘np.flip( )’
(1) np.flip( )
- Reverse the order of elements in an array along the given axis.
- The shape of the array is preserved, but the elements are reordered.
Syntax:
numpy.flip(m, axis=None)
Parameters:
- m: array_like – Input array.
- axis: None or int or tuple of ints, optional – Axis or axes along which to flip over. The default, axis=None, will flip over all of the axes of the input array. If axis is negative it counts from the last to the first axis.If axis is a tuple of ints, flipping is performed on all of the axes specified in the tuple.
Returns:
- out: array_like – A view of m with the entries of axis reversed. Since a view is returned, this operation is done in constant time.
(2) Examples Of np.flip( )
Example-1:Reversing A 1D array
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
arr
array([1, 2, 3, 4, 5, 6, 7, 8])
reversed_arr = np.flip(arr)
reversed_arr
array([8, 7, 6, 5, 4, 3, 2, 1])
Example-2:Reversing A 2D array
import numpy as np
arr_2d = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
arr_2d
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]])
reversed_arr = np.flip(arr_2d)
reversed_arr
array([[12, 11, 10, 9],
[ 8, 7, 6, 5],
[ 4, 3, 2, 1]])
Example-3:Reversing Only Rows
import numpy as np
arr_2d = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
arr_2d
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]])
reversed_arr_rows = np.flip(arr_2d, axis=0)
reversed_arr_rows
array([[ 9, 10, 11, 12],
[ 5, 6, 7, 8],
[ 1, 2, 3, 4]])
Example-4:Reversing Only Columns
import numpy as np
arr_2d = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
arr_2d
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]])
reversed_arr_columns = np.flip(arr_2d, axis=1)
reversed_arr_columns
array([[ 4, 3, 2, 1],
[ 8, 7, 6, 5],
[12, 11, 10, 9]])