Create a two-dimensional array with the flattened input as a diagonal in Numpy


To create a two-dimensional array with the flattened input as a diagonal, use the numpy.diagflat() method in Python Numpy. The first parameter is the input data, which is flattened and set as the kth diagonal of the output. The second parameter is the diagonal to set; 0, the default, corresponds to the “main” diagonal, a positive (negative) k giving the number of the diagonal above (below) the main.

NumPy offers comprehensive mathematical functions, random number generators, linear algebra routines, Fourier transforms, and more. It supports a wide range of hardware and computing platforms, and plays well with distributed, GPU, and sparse array libraries.

Steps

At first, import the required library −

import numpy as np

Create a 2D array using the numpy.array() method −

arr = np.array([[5, 10], [15, 20]])

Displaying our array −

print("Array...
",arr)

Get the datatype −

print("
Array datatype...
",arr.dtype)

Get the dimensions of the Array −

print("
Array Dimensions...
",arr.ndim)

Get the shape of the Array −

print("
Our Array Shape...
",arr.shape)

Get the number of elements of the Array −

print("
Elements in the Array...
",arr.size)

To create a two-dimensional array with the flattened input as a diagonal, use the numpy.diagflat() method −

print("
Result...
",np.diagflat(arr))

Example

import numpy as np
# Create a 2D array using the numpy.array() method
arr = np.array([[5, 10], [15, 20]])

# Displaying our array
print("Array...
",arr) # Get the datatype print("
Array datatype...
",arr.dtype) # Get the dimensions of the Array print("
Array Dimensions...
",arr.ndim) # Get the shape of the Array print("
Our Array Shape...
",arr.shape) # Get the number of elements of the Array print("
Elements in the Array...
",arr.size) # To create a two-dimensional array with the flattened input as a diagonal, use the numpy.diagflat() method in Python Numpy print("
Result...
",np.diagflat(arr))

Output

Array...
[[ 5 10]
[15 20]]

Array datatype...
int64

Array Dimensions...
2

Our Array Shape...
(2, 2)

Elements in the Array...
4

Result...
[[ 5 0 0 0]
[ 0 10 0 0]
[ 0 0 15 0]
[ 0 0 0 20]]

Updated on: 16-Feb-2022

280 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements