
- NumPy - Home
- NumPy - Introduction
- NumPy - Environment
- NumPy Arrays
- NumPy - Ndarray Object
- NumPy - Data Types
- NumPy Creating and Manipulating Arrays
- NumPy - Array Creation Routines
- NumPy - Array Manipulation
- NumPy - Array from Existing Data
- NumPy - Array From Numerical Ranges
- NumPy - Iterating Over Array
- NumPy - Reshaping Arrays
- NumPy - Concatenating Arrays
- NumPy - Stacking Arrays
- NumPy - Splitting Arrays
- NumPy - Flattening Arrays
- NumPy - Transposing Arrays
- NumPy Indexing & Slicing
- NumPy - Indexing & Slicing
- NumPy - Indexing
- NumPy - Slicing
- NumPy - Advanced Indexing
- NumPy - Fancy Indexing
- NumPy - Field Access
- NumPy - Slicing with Boolean Arrays
- NumPy Array Attributes & Operations
- NumPy - Array Attributes
- NumPy - Array Shape
- NumPy - Array Size
- NumPy - Array Strides
- NumPy - Array Itemsize
- NumPy - Broadcasting
- NumPy - Arithmetic Operations
- NumPy - Array Addition
- NumPy - Array Subtraction
- NumPy - Array Multiplication
- NumPy - Array Division
- NumPy Advanced Array Operations
- NumPy - Swapping Axes of Arrays
- NumPy - Byte Swapping
- NumPy - Copies & Views
- NumPy - Element-wise Array Comparisons
- NumPy - Filtering Arrays
- NumPy - Joining Arrays
- NumPy - Sort, Search & Counting Functions
- NumPy - Searching Arrays
- NumPy - Union of Arrays
- NumPy - Finding Unique Rows
- NumPy - Creating Datetime Arrays
- NumPy - Binary Operators
- NumPy - String Functions
- NumPy - Matrix Library
- NumPy - Linear Algebra
- NumPy - Matplotlib
- NumPy - Histogram Using Matplotlib
- NumPy Sorting and Advanced Manipulation
- NumPy - Sorting Arrays
- NumPy - Sorting along an axis
- NumPy - Sorting with Fancy Indexing
- NumPy - Structured Arrays
- NumPy - Creating Structured Arrays
- NumPy - Manipulating Structured Arrays
- NumPy - Record Arrays
- Numpy - Loading Arrays
- Numpy - Saving Arrays
- NumPy - Append Values to an Array
- NumPy - Swap Columns of Array
- NumPy - Insert Axes to an Array
- NumPy Handling Missing Data
- NumPy - Handling Missing Data
- NumPy - Identifying Missing Values
- NumPy - Removing Missing Data
- NumPy - Imputing Missing Data
- NumPy Performance Optimization
- NumPy - Performance Optimization with Arrays
- NumPy - Vectorization with Arrays
- NumPy - Memory Layout of Arrays
- Numpy Linear Algebra
- NumPy - Linear Algebra
- NumPy - Matrix Library
- NumPy - Matrix Addition
- NumPy - Matrix Subtraction
- NumPy - Matrix Multiplication
- NumPy - Element-wise Matrix Operations
- NumPy - Dot Product
- NumPy - Matrix Inversion
- NumPy - Determinant Calculation
- NumPy - Eigenvalues
- NumPy - Eigenvectors
- NumPy - Singular Value Decomposition
- NumPy - Solving Linear Equations
- NumPy - Matrix Norms
- NumPy Element-wise Matrix Operations
- NumPy - Sum
- NumPy - Mean
- NumPy - Median
- NumPy - Min
- NumPy - Max
- NumPy Set Operations
- NumPy - Unique Elements
- NumPy - Intersection
- NumPy - Union
- NumPy - Difference
- NumPy Random Number Generation
- NumPy - Random Generator
- NumPy - Permutations & Shuffling
- NumPy - Uniform distribution
- NumPy - Normal distribution
- NumPy - Binomial distribution
- NumPy - Poisson distribution
- NumPy - Exponential distribution
- NumPy - Rayleigh Distribution
- NumPy - Logistic Distribution
- NumPy - Pareto Distribution
- NumPy - Visualize Distributions With Sea born
- NumPy - Matplotlib
- NumPy - Multinomial Distribution
- NumPy - Chi Square Distribution
- NumPy - Zipf Distribution
- NumPy File Input & Output
- NumPy - I/O with NumPy
- NumPy - Reading Data from Files
- NumPy - Writing Data to Files
- NumPy - File Formats Supported
- NumPy Mathematical Functions
- NumPy - Mathematical Functions
- NumPy - Trigonometric functions
- NumPy - Exponential Functions
- NumPy - Logarithmic Functions
- NumPy - Hyperbolic functions
- NumPy - Rounding functions
- NumPy Fourier Transforms
- NumPy - Discrete Fourier Transform (DFT)
- NumPy - Fast Fourier Transform (FFT)
- NumPy - Inverse Fourier Transform
- NumPy - Fourier Series and Transforms
- NumPy - Signal Processing Applications
- NumPy - Convolution
- NumPy Polynomials
- NumPy - Polynomial Representation
- NumPy - Polynomial Operations
- NumPy - Finding Roots of Polynomials
- NumPy - Evaluating Polynomials
- NumPy Statistics
- NumPy - Statistical Functions
- NumPy - Descriptive Statistics
- NumPy Datetime
- NumPy - Basics of Date and Time
- NumPy - Representing Date & Time
- NumPy - Date & Time Arithmetic
- NumPy - Indexing with Datetime
- NumPy - Time Zone Handling
- NumPy - Time Series Analysis
- NumPy - Working with Time Deltas
- NumPy - Handling Leap Seconds
- NumPy - Vectorized Operations with Datetimes
- NumPy ufunc
- NumPy - ufunc Introduction
- NumPy - Creating Universal Functions (ufunc)
- NumPy - Arithmetic Universal Function (ufunc)
- NumPy - Rounding Decimal ufunc
- NumPy - Logarithmic Universal Function (ufunc)
- NumPy - Summation Universal Function (ufunc)
- NumPy - Product Universal Function (ufunc)
- NumPy - Difference Universal Function (ufunc)
- NumPy - Finding LCM with ufunc
- NumPy - ufunc Finding GCD
- NumPy - ufunc Trigonometric
- NumPy - Hyperbolic ufunc
- NumPy - Set Operations ufunc
- NumPy Useful Resources
- NumPy - Quick Guide
- NumPy - Cheatsheet
- NumPy - Useful Resources
- NumPy - Discussion
- NumPy Compiler
Numpy diag() Function
The Numpy diag() function is used to either extract the diagonal elements from a matrix (2D array) or create a diagonal matrix from a 1D array or list. This function is used in matrix operations and numerical computations.
The numpy.diag() function can be used in two different ways:
- In case of 2D array, the function extracts the diagonal elements of the array.
- In case of 1D array, the function creates a square diagonal matrix with the elements of the 1D array as the diagonal values and zeros in reamining positions.
Syntax
Following is the syntax of the Numpy diag() function −
numpy.diag(array, k=0)
Parameters
Following are the parameters of the Numpy diag() function −
- array: This represents input array(can be array_like)
- k(Optional): This is an integer number representing the diagonal to retrieve −
- k>0 - represents diagonals above the main diagonal
- k<0 - represents diagonals below the main diagonal
Return Value
The function either returns the diagonal elements of a 2D array or a new square 2D array (diagonal matrix) when provided with a 1D array.
Example
Following is a basic example to extract the diagonal elements from a given 2D array using Numpy diag() function −
import numpy as np Matrix = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]]) print("Original Array:\n", Matrix) Diagonal_elements = np.diag(Matrix) print("Diagonal Elements:", Diagonal_elements)
Output
Following is the output of the above code:
Original Array: [[10 20 30] [40 50 60] [70 80 90]] Diagonal Elements: [10 50 90]
Example : Creating a Diagonal Matrix
When a 1D array is passed to the numpy.diag() function, it creates a square matrix with the elements of the array on the main diagonal and zeros elsewhere.
In the following example, we have created a diagonal matrix from a given 1D array −
import numpy as np array = np.array([1, 2, 3, 4]) print("Original Array:",array) diagonal_matrix = np.diag(array) print("Diagonal Matrix:\n", diagonal_matrix)
Output
Following is the output of the above code −
Original Array: [1 2 3 4] Diagonal Matrix: [[1 0 0 0] [0 2 0 0] [0 0 3 0] [0 0 0 4]]
Example : Specifying Diagonal Offset
The k parameter can be used to specify which diagonal to extract or set. Positive values extract diagonals above the main diagonal, while negative values extract diagonals below the main diagonal.
'k' with Positive Integer
In the following example, we have extracted the diagonal elements that is one step above the main diagonal (k=1) −
import numpy as np matrix = np.array([[11, 22, 33], [44, 55, 66], [77, 88, 99]]) print("Original Array:\n",matrix) diagonal_above = np.diag(matrix, k=1) print("Diagonal Above Main Diagonal:", diagonal_above)
Output
Following is the output of the above code −
Original Array: [[11 22 33] [44 55 66] [77 88 99]] Diagonal Above Main Diagonal: [22 66]
'k' with Negative Integer
In the following example, we have created a diagonal matrix where the diagonal is one step below the main diagonal (k=-1) −
import numpy as np array = np.array([[11, 22, 33], [44, 55, 66], [77, 88, 99]]) print("Original Array:\n",array) diagonal_matrix_below = np.diag(array, k=-1) print("Diagonal Matrix Below Main Diagonal:", diagonal_matrix_below)
Output
Following is the output of the above code −
Original Array: [[11 22 33] [44 55 66] [77 88 99]] Diagonal Matrix Below Main Diagonal: [44 88]
Example : Specifying Different Data Types
We can specify the data type of the elements in the diagonal matrix by setting the dtype attribute when creating the array before passing it to numpy.diag().
In the following example, we have created a diagonal matrix of float data type −
import numpy as np Float_array = np.array([10, 20, 30], dtype=float) Float_diagonal_matrix = np.diag(Float_array) print("Float Diagonal Matrix:\n", Float_diagonal_matrix)
Output
Float Diagonal Matrix: [[10. 0. 0.] [ 0. 20. 0.] [ 0. 0. 30.]]
Example : Passing a Float value for 'k'
When we provide a non-integer value for the k parameter or pass invalid data types, numpy.diag() will raise TypeError.
In the following example, we have passed the k value as a float point which resulted an error −
import numpy as np array = np.array([1, 2, 3]) # This will raise a TypeError diagonal_matrix_float_k = np.diag(array, k=1.5) print(diagonal_matrix_float_k)
Output
Traceback (most recent call last): File "/home/cg/root/46524/main.py", line 4, in <module> diagonal_matrix_float_k = np.diag(array, k=1.5) File "<__array_function__ internals>", line 200, in diag File "/usr/local/lib/python3.10/dist-packages/numpy/lib/twodim_base.py", line 299, in diag res = zeros((n, n), v.dtype) TypeError: 'float' object cannot be interpreted as an integer