The flip()
method reverses the order of the elements in an array.
Example
import numpy as np
# create an array
array1 = np.array([0, 1, 2, 3, 4])
# flip the elements of array1
array2 = np.flip(array1)
print(array2)
# Output: [4 3 2 1 0]
flip() Syntax
The syntax of flip()
is:
numpy.flip(array, axis = None)
flip() Arguments
The flip()
method takes two arguments:
array
- an array with elements to be flippedaxis
(optional) - axis to flip (None
orint
ortuple
)
flip() Return Value
The flip()
method returns the array with elements reversed.
Example 1: Flip a 2-D Array
A 2-D array can be flipped on two axes. If the array is flipped on axis 0, it is reversed vertically and if the array is flipped on axis 1, it is reversed horizontally.
import numpy as np
# create an array
array1 = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
# flip the elements of array1
array2 = np.flip(array1)
# flip array1 vertically
array3 = np.flip(array1, axis = 0)
# flip array1 horizontally
array4 = np.flip(array1, axis = 1)
print('\n Flipped Array: \n', array2)
print('\n Array flipped along axis 0\n', array3)
print('\n Array flipped along axis 1\n', array4)
Output
Flipped Array: [[8 7 6] [5 4 3] [2 1 0]] Array flipped along axis 0 [[6 7 8] [3 4 5] [0 1 2]] Array flipped along axis 1 [[2 1 0] [5 4 3] [8 7 6]]
Here, we haven't passed axis
in array2, so the array is flattened, flipped, and reshaped back to its original shape.
Example 2: Flip a 3-D Array on Multiple Axes
import numpy as np
# create an array
array1 = np.array([[[0, 1], [2, 3]],
[[4, 5], [6, 7]]])
# flip the elements of array1 along axis 0
array2 = np.flip(array1, axis = 0)
# flip the elements of array1 along axis 1
array3 = np.flip(array1, axis = 1)
# flip the elements of array1 along both axis 0 and 1
array4 = np.flip(array1, (0, 1))
print('\n Array flipped on axis 0: \n', array2)
print('\n Array flipped on axis 1: \n', array3)
print('\n Array flipped on axes 0 and 1: \n', array4)
Output
Array flipped on axis 0: [[[4 5] [6 7]] [[0 1] [2 3]]] Array flipped on axis 1: [[[4 5] [6 7]] [[0 1] [2 3]]] Array flipped on axes 0 and 1: [[[6 7] [4 5]] [[2 3] [0 1]]]
Example 3: Flip with flipup() and fliplr()
Instead of using the axis
parameter, we can simply use flipud()
to flip vertically and fliplr()
to flip horizontally.
import numpy as np
# create an array
array1 = np.array([[0, 1], [2, 3]])
# flip the elements of array1 vertically
array2 = np.flipud(array1)
# flip the elements of array1 horizontally
array3 = np.fliplr(array1)
print('\n Array flipped vertically : \n',array2)
print('\n Array flipped horizontally : \n',array3)
Output
Array flipped vertically : [[2 3] [0 1]] Array flipped horizontally : [[1 0] [3 2]]