How to get the opposite diagonal of a NumPy array?

Given a NumPy array, we have to get the opposite diagonal from it.
By Pranit Sharma Last updated : December 27, 2023

Diagonals of an array are defined as a set of those points where the row and the column coordinates are the same.

Problem statement

Suppose that we are given a multi-dimensional numpy array and we need to get the opposite diagonals of this array. By this, we mean that we need to get the diagonal starting from the top right rather than the top left. Numpy has a built-in function for the diagonal indices but there is no direct option to get the opposite diagonals.

Getting the opposite diagonal

To get the opposite diagonal, we can simply use the numpy.rot90() function to rotate the numpy array with 90 degrees and then we can apply the numpy.diag() function on the rotated array.

Below is the syntax of numpy.rot90() method:

numpy.rot90(m, k=1, axes=(0, 1))

Let us understand with the help of an example,

Python code to get the opposite diagonal of a NumPy array

# Import numpy
import numpy as np

# Creating a numpy array
arr = np.arange(25).reshape(5,5)

# Display Original array
print("Original array:\n",arr,"\n\n")

# Rotating the array
rot = np.rot90(arr)

# Getting opposite diagonals
res = np.diag(rot)

# Display result


Example: How to get the opposite diagonal of a NumPy array?

In this example, we have used the following Python basic topics that you should learn:

Python NumPy Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.