In this article we will discuss different ways to reverse the contents of 1D and 2D numpy array ( columns & rows ) using np.flip() and [] operator.

Reverse 1D Numpy array using [] operator trick

First of all import numpy module i.e.

Now suppose we have a numpy array i.e.

Now let’s reverse the contents of the above created numpy array using a small trick,

Output:

How did it worked ?

In numpy array we use the [] operator with following syntax,

It will basically select the elements from start to end with step size as stepsize. We did not provided start and end parameter, therefore by default it picked the complete array. Also, the step size was -1, therefore it selected the elements from last to first.

Reverse Array is View Only

reversedArr is just a reversed view of the arr. It means any modification in this view reversedArr will also be reflected in the original array arr i.e.

Output:

Reverse Numpy array using np.flip()

Python’s Numpy module provides a function to flip the contents of numpy array along different axis i.e.

Arguments:

  • arr : Numpy array
  • axis : Axis along which it needs to flip / reverse the contents.
    • If None: flip / reverse contents along all of the axes of the input array

Let’s understand by examples,

Reverse 1D Numpy array using np.flip()

Suppose we have a numpy array i.e.

Now let’s reverse the contents of the above created numpy array using a np.flip(),

Output:

As it was 1D numpy array, so we don’t need to provide axis parameter.

Reverse 2D Numpy Array using np.flip()

Let’s create a 2D Numpy array i.e.

Contents of the 2D numpy array are,

Reverse contents in all rows and all columns of 2D Numpy Array

If we don’t provide any axis parameter in np.flip() then fit will reverse contents along all of the axes of the 2D array i.e.

Output:

It flipped contents in all rows and all columns of 2D Numpy Array

Reverse contents of all rows only in 2D Numpy Array

Output:

Reverse contents of all columns only in 2D Numpy Array

Output:

Reverse contents of only one column in 2D Numpy Array

Output:

It flipped the contents of 2nd column only in numpy array.

Reverse contents of only one row in 2D Numpy Array

Output:

It flipped the contents of 2nd row only in numpy array.

Complete example is as follows :

Output:

Join LinkedIn Group of Python Professional Developers who wish to expand their network and share ideas.

You can also follow us On Twitter :

Click Here to Subscribe for more Articles / Tutorials like this.