- numpy.diag#
- numpy.diagonal#
- Функция np.diag() в Python с примерами
- Что такое функция np.diag() в Python?
- Синтаксис
- Параметры
- Возвращаемое значение
- Примеры программ для метода diag() в Python
- Пример 1
- Пример 2
- Numpy – Create a Diagonal Matrix (With Examples)
- How to create a diagonal matrix with Numpy?
- Examples
- Example 1 – Diagonal matrix from 1d array placed on the default diagonal in Numpy
- Example 2 – Diagonal matrix from 1d array placed on a custom diagonal in Numpy
- Alternative usage of the numpy.diag() function
- Summary
- Author
numpy.diag#
See the more detailed documentation for numpy.diagonal if you use this function to extract a diagonal and wish to write to the resulting array; whether it returns a copy or a view depends on what version of numpy you are using.
Parameters : v array_like
If v is a 2-D array, return a copy of its k-th diagonal. If v is a 1-D array, return a 2-D array with v on the k-th diagonal.
k int, optional
Diagonal in question. The default is 0. Use k>0 for diagonals above the main diagonal, and k for diagonals below the main diagonal.
Returns : out ndarray
The extracted diagonal or constructed diagonal array.
Return specified diagonals.
Create a 2-D array with the flattened input as a diagonal.
Upper triangle of an array.
Lower triangle of an array.
>>> x = np.arange(9).reshape((3,3)) >>> x array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
>>> np.diag(x) array([0, 4, 8]) >>> np.diag(x, k=1) array([1, 5]) >>> np.diag(x, k=-1) array([3, 7])
>>> np.diag(np.diag(x)) array([[0, 0, 0], [0, 4, 0], [0, 0, 8]])
numpy.diagonal#
If a is 2-D, returns the diagonal of a with the given offset, i.e., the collection of elements of the form a[i, i+offset] . If a has more than two dimensions, then the axes specified by axis1 and axis2 are used to determine the 2-D sub-array whose diagonal is returned. The shape of the resulting array can be determined by removing axis1 and axis2 and appending an index to the right equal to the size of the resulting diagonals.
In versions of NumPy prior to 1.7, this function always returned a new, independent array containing a copy of the values in the diagonal.
In NumPy 1.7 and 1.8, it continues to return a copy of the diagonal, but depending on this fact is deprecated. Writing to the resulting array continues to work as it used to, but a FutureWarning is issued.
Starting in NumPy 1.9 it returns a read-only view on the original array. Attempting to write to the resulting array will produce an error.
In some future release, it will return a read/write view and writing to the returned array will alter your original array. The returned array will have the same type as the input array.
If you don’t write to the array returned by this function, then you can just ignore all of the above.
If you depend on the current behavior, then we suggest copying the returned array explicitly, i.e., use np.diagonal(a).copy() instead of just np.diagonal(a) . This will work with both past and future versions of NumPy.
Parameters : a array_like
Array from which the diagonals are taken.
offset int, optional
Offset of the diagonal from the main diagonal. Can be positive or negative. Defaults to main diagonal (0).
axis1 int, optional
Axis to be used as the first axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults to first axis (0).
axis2 int, optional
Axis to be used as the second axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults to second axis (1).
Returns : array_of_diagonals ndarray
If a is 2-D, then a 1-D array containing the diagonal and of the same type as a is returned unless a is a matrix , in which case a 1-D array rather than a (2-D) matrix is returned in order to maintain backward compatibility.
If a.ndim > 2 , then the dimensions specified by axis1 and axis2 are removed, and a new axis inserted at the end corresponding to the diagonal.
If the dimension of a is less than 2.
MATLAB work-a-like for 1-D and 2-D arrays.
>>> a = np.arange(4).reshape(2,2) >>> a array([[0, 1], [2, 3]]) >>> a.diagonal() array([0, 3]) >>> a.diagonal(1) array([1])
>>> a = np.arange(8).reshape(2,2,2); a array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]]) >>> a.diagonal(0, # Main diagonals of two arrays created by skipping . 0, # across the outer(left)-most axis last and . 1) # the "middle" (row) axis first. array([[0, 6], [1, 7]])
The sub-arrays whose main diagonals we just obtained; note that each corresponds to fixing the right-most (column) axis, and that the diagonals are “packed” in rows.
>>> a[. 0] # main diagonal is [0 6] array([[0, 2], [4, 6]]) >>> a[. 1] # main diagonal is [1 7] array([[1, 3], [5, 7]])
The anti-diagonal can be obtained by reversing the order of elements using either numpy.flipud or numpy.fliplr .
>>> a = np.arange(9).reshape(3, 3) >>> a array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> np.fliplr(a).diagonal() # Horizontal flip array([2, 4, 6]) >>> np.flipud(a).diagonal() # Vertical flip array([6, 4, 2])
Note that the order in which the diagonal is retrieved varies depending on the flip function.
Функция np.diag() в Python с примерами
Функция np.diag() определена в библиотеке numpy, которую можно импортировать как import numpy as np. Мы можем создавать многомерные массивы и получать другую математическую статистику с помощью numpy. Имя функции Python diag() происходит от diagonal.
Что такое функция np.diag() в Python?
Функция np.diag() извлекает и создает диагональный массив на Python. Она принимает массив и k в качестве параметров и возвращает диагональный массив из заданного массива.
Синтаксис
Параметры
Функция принимает два параметра, один из которых является необязательным.
- Первый параметр — это входной массив, представленный arr.
- Второй параметр — k, является необязательным и по умолчанию принимает значение 0. Если значение этого параметра больше 0, это означает, что диагональ находится выше главной диагонали, и наоборот, если нет.
Возвращаемое значение
Возвращает массив с диагональным массивом.
Примеры программ для метода diag() в Python
Напишем программу, показывающую работу функции diag() в Python.
Пример 1
В этом примере мы используем numpy diag() и можем видеть, что, передавая разные значения k, можем получить их диагональные элементы. Здесь мы увидели главную диагональ в матрице, затем диагональ выше главной диагонали при передаче значения k=1 и наоборот при передаче значения k=-1.
Пример 2
Напишем программу, которая берет матрицу 4×4 и применяет функцию diag().
Numpy – Create a Diagonal Matrix (With Examples)
The Numpy library in Python comes with a number of useful functions to work with and manipulate the data in arrays. In this tutorial, we will look at how to create a diagonal matrix using Numpy with the help of some examples.
How to create a diagonal matrix with Numpy?
You can use the numpy built-in numpy.diag() function to create a diagonal matrix. Pass the 1d array of the diagonal elements.
📚 Discover Online Data Science Courses & Programs (Enroll for Free)
Introductory ⭐
Intermediate ⭐⭐⭐
🔎 Find Data Science Programs 👨💻 111,889 already enrolled
Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.
The following is the syntax –
To create a diagonal matrix you can use the following parameters –
- v – The 1d array containing the diagonal elements.
- k – The diagonal on which the passed elements (elements of the 1d array, v) are to be placed. By default, k is 0 which refers to the main diagonal. Diagonals above the main diagonal are positive and the ones below it are negative (see the examples below).
It returns a 2d array with the passed elements placed on the kth diagonal.
Examples
Let’s now look at examples of using the above syntax to get create a diagonal matrix using the Numppy library.
Example 1 – Diagonal matrix from 1d array placed on the default diagonal in Numpy
Let’s now use the numpy.diag() function to create a diagonal matrix from a 1d array. For example, we’ll only pass the 1d array and use the default diagonal.
import numpy as np # create a 1d array of diagonal elements ar = np.array([1, 2, 3]) # create a diagonal matrix res = np.diag(ar) # display the returned matrix print(res)
We get a 2d numpy array which is a diagonal matrix. All the elements in the matrix are zero except the diagonal elements. You can see that the passed elements are placed on the main diagonal ( k=0 ).
Example 2 – Diagonal matrix from 1d array placed on a custom diagonal in Numpy
In the above example, we placed the elements from the 1d array of the main diagonal.
The numpy.diag() function comes with an optional parameter, k that you can use to specify the diagonal you want to use to create the diagonal matrix.
The below image better illustrates the different values of k (representing different diagonals) for a 3×3 matrix.
k is 0 by default. The diagonals below the main diagonal have k < 0 and the diagonals above it have k >0 .
Let’s now use the numpy.diag() function to create a diagonal matrix by placing the passed elements on the k=-1 diagonal.
# create a 1d array of diagonal elements ar = np.array([1, 2, 3]) # create a diagonal matrix with elements on digonal, k=-1 res = np.diag(ar, k=-1) # display the returned matrix print(res)
[[0 0 0 0] [1 0 0 0] [0 2 0 0] [0 0 3 0]]
The resulting diagonal matrix has the passed elements on the k = -1 diagonal. Here, the resulting matrix is 4×4 because all the elements in the passed array cannot be accommodated on the k=-1 diagonal of a 3×3 matrix, hence the added dimensions.
Alternative usage of the numpy.diag() function
In the above examples, we used the numpy.diag() function to create a diagonal matrix by passing a 1d array and placing its elements on the kth diagonal.
You can also use the numpy.diag() function to extract the diagonal elements from a 2d array.
For example, if you pass a 2d array to the numpy.diag() function, it will return its diagonal elements on the kth diagonal (which is 0 by default).
# create a 2D numpy array arr = np.array([ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]) # get the diagonal elements res = np.diag(arr) # display the diagonal elements print(res)
We get the elements on the main diagonal as a 1d array.
Summary
In this tutorial, we looked at how to create a diagonal matrix using a 1d array in Numpy. The following are the key takeaways from this tutorial.
- Use the numpy.diag() function to create a diagonal matrix. Pass the diagonal elements as a 1d array.
- You can specify the diagonal to place the elements in the passed array on using the optional parameter k . By default, it represents the main diagonal, k = 0 .
You might also be interested in –
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.
Author
Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects. View all posts
Data Science Parichay is an educational website offering easy-to-understand tutorials on topics in Data Science with the help of clear and fun examples.