Создание матрицы numpy python

numpy.matrix#

It is no longer recommended to use this class, even for linear algebra. Instead use regular arrays. The class may be removed in the future.

Returns a matrix from an array-like object, or from a string of data. A matrix is a specialized 2-D array that retains its 2-D nature through operations. It has certain special operators, such as * (matrix multiplication) and ** (matrix power).

Parameters : data array_like or string

If data is a string, it is interpreted as a matrix with commas or spaces separating columns, and semicolons separating rows.

dtype data-type

Data-type of the output matrix.

If data is already an ndarray , then this flag determines whether the data is copied (the default), or whether a view is constructed.

>>> a = np.matrix('1 2; 3 4') >>> a matrix([[1, 2], [3, 4]]) 
>>> np.matrix([[1, 2], [3, 4]]) matrix([[1, 2], [3, 4]]) 

Return self as an ndarray object.

Return self as a flattened ndarray .

Returns the (complex) conjugate transpose of self.

Returns the (multiplicative) inverse of invertible self.

Returns the transpose of the matrix.

Base object if memory is from some other object.

An object to simplify the interaction of the array with the ctypes module.

Python buffer object pointing to the start of the array’s data.

Data-type of the array’s elements.

Information about the memory layout of the array.

A 1-D iterator over the array.

The imaginary part of the array.

Length of one array element in bytes.

Total bytes consumed by the elements of the array.

Number of array dimensions.

The real part of the array.

Tuple of array dimensions.

Number of elements in the array.

Tuple of bytes to step in each dimension when traversing an array.

Test whether all matrix elements along a given axis evaluate to True.

Test whether any array element along a given axis evaluates to True.

Indexes of the maximum values along an axis.

Indexes of the minimum values along an axis.

Returns the indices that would partition this array.

Returns the indices that would sort this array.

astype (dtype[, order, casting, subok, copy])

Copy of the array, cast to a specified type.

Swap the bytes of the array elements

Use an index array to construct a new array from a set of choices.

Return an array whose values are limited to [min, max] .

Return selected slices of this array along given axis.

Complex-conjugate all elements.

Return the complex conjugate, element-wise.

Return a copy of the array.

Return the cumulative product of the elements along the given axis.

Return the cumulative sum of the elements along the given axis.

Return specified diagonals.

Dump a pickle of the array to the specified file.

Returns the pickle of the array as a string.

Fill the array with a scalar value.

Return a flattened copy of the matrix.

Return self as an ndarray object.

Return self as a flattened ndarray .

Returns the (complex) conjugate transpose of self.

Returns the (multiplicative) inverse of invertible self.

Returns the transpose of the matrix.

Returns a field of the given array as a certain type.

Copy an element of an array to a standard Python scalar and return it.

Insert scalar into an array (scalar is cast to array’s dtype, if possible)

Return the maximum value along an axis.

Returns the average of the matrix elements along the given axis.

Return the minimum value along an axis.

Return the array with the same data viewed with a different byte order.

Return the indices of the elements that are non-zero.

Rearranges the elements in the array in such a way that the value of the element in kth position is in the position it would be in a sorted array.

Return the product of the array elements over the given axis.

Peak-to-peak (maximum — minimum) value along the given axis.

Set a.flat[n] = values[n] for all n in indices.

Return a flattened matrix.

Repeat elements of an array.

Returns an array containing the same data with a new shape.

Change shape and size of array in-place.

Return a with each element rounded to the given number of decimals.

Find indices where elements of v should be inserted in a to maintain order.

Put a value into a specified place in a field defined by a data-type.

Set array flags WRITEABLE, ALIGNED, WRITEBACKIFCOPY, respectively.

Return a possibly reshaped matrix.

Return the standard deviation of the array elements along the given axis.

Returns the sum of the matrix elements, along the given axis.

Return a view of the array with axis1 and axis2 interchanged.

Return an array formed from the elements of a at the given indices.

Construct Python bytes containing the raw data bytes in the array.

Write array to a file as text or binary (default).

Return the matrix as a (possibly nested) list.

A compatibility alias for tobytes , with exactly the same behavior.

trace ([offset, axis1, axis2, dtype, out])

Return the sum along diagonals of the array.

Returns a view of the array with axes transposed.

Returns the variance of the matrix elements, along the given axis.

New view of array with the same data.

Источник

Матрицы в Python и массивы NumPy

Матрица — это двухмерная структура данных, в которой числа расположены в виде строк и столбцов. Например:

Эта матрица является матрицей три на четыре, потому что она состоит из 3 строк и 4 столбцов.

Матрицы в Python

Python не имеет встроенного типа данных для матриц. Но можно рассматривать список как матрицу. Например:

Этот список является матрицей на 2 строки и 3 столбца.

Матрицы в Python

Обязательно ознакомьтесь с документацией по спискам Python , прежде чем продолжить читать эту статью.

Давайте посмотрим, как работать с вложенным списком.

A = [[1, 4, 5, 12], [-5, 8, 9, 0], [-6, 7, 11, 19]] print("A =", A) print("A[1] =", A[1]) # вторая строка print("A[1][2] =", A[1][2]) # третий элемент второй строки print("A[0][-1] =", A[0][-1]) # последний элемент первой строки column = []; # пустой список for row in A: column.append(row[2]) print("3rd column 1" data-ab-test="post_related" data-ab-key="yarpp">
Как работают массивы в Python?

Когда мы запустим эту программу, результат будет следующий:

A = [[1, 4, 5, 12], [-5, 8, 9, 0], [-6, 7, 11, 19]] A [1] = [-5, 8, 9, 0] A [1] [2] = 9 A [0] [- 1] = 12 3-й столбец = [5, 9, 11]

Использование вложенных списков в качестве матрицы подходит для простых вычислительных задач. Но в Python есть более эффективный способ работы с матрицами – NumPy .

NumPy массивы в Python

NumPy - это расширение для научных вычислений, которое поддерживает мощный объект N-мерного массива. Прежде чем использовать NumPy, необходимо установить его. Для получения дополнительной информации,

  • Ознакомьтесь: Как установить NumPy Python?
  • Если вы работаете в Windows, скачайте и установите дистрибутив anaconda Python. Он поставляется вместе с NumPy и другими расширениями.

После установки NumPy можно импортировать и использовать его.

NumPy предоставляет собой многомерный массив чисел (который на самом деле является объектом). Давайте рассмотрим приведенный ниже пример:

import numpy as np a = np.array([1, 2, 3]) print(a) # Вывод: [1, 2, 3] print(type(a)) # Вывод:

Как видите, класс массива NumPy называется ndarray.

Как создать массив NumPy?

Существует несколько способов создания массивов NumPy.

Массив целых чисел, чисел с плавающей точкой и составных чисел

import numpy as np A = np.array([[1, 2, 3], [3, 4, 5]]) print(A) A = np.array([[1.1, 2, 3], [3, 4, 5]]) # Массив чисел с плавающей запятой print(A) A = np.array([[1, 2, 3], [3, 4, 5]], dtype = complex) # Массив составных чисел print(A)

Когда вы запустите эту программу, результат будет следующий:

[[1 2 3] [3 4 5]] [[1.1 2. 3.] [3. 4. 5.]] [[1. + 0.j 2. + 0.j 3. + 0.j] [3. + 0.j 4. + 0.j 5. + 0.j]]

Массив нулей и единиц

import numpy as np zeors_array = np.zeros( (2, 3) ) print(zeors_array) ''' Вывод: [[0. 0. 0.] [0. 0. 0.]] ''' ones_array = np.ones( (1, 5), dtype=np.int32 ) // указание dtype print(ones_array) # Вывод: [[1 1 1 1 1]]

Здесь мы указали dtype - 32 бита (4 байта). Следовательно, этот массив может принимать значения от -2 -31 до 2 -31 -1.

Использование arange() и shape()

import numpy as np A = np.arange(4) print('A =', A) B = np.arange(12).reshape(2, 6) print('B =', B) ''' Вывод: A = [0 1 2 3] B = [[ 0 1 2 3 4 5] [ 6 7 8 9 10 11]] '''

Узнайте больше о других способах создания массива NumPy .

Операции с матрицами

Выше мы привели пример сложение, умножение матриц и транспонирование матрицы. Мы использовали вложенные списки, прежде чем создавать эти программы. Рассмотрим, как выполнить ту же задачу, используя массив NumPy.

Сложение двух матриц или сумма элементов массива Python

Мы используем оператор +, чтобы сложить соответствующие элементы двух матриц NumPy.

import numpy as np A = np.array([[2, 4], [5, -6]]) B = np.array([[9, -3], [3, 6]]) C = A + B # сложение соответствующих элементов print(C) ''' Вывод: [[11 1] [ 8 0]] '''

Умножение двух матриц Python

Чтобы умножить две матрицы, мы используем метод dot(). Узнайте больше о том, как работает numpy.dot .

Примечание: * используется для умножения массива (умножения соответствующих элементов двух массивов), а не умножения матрицы.

import numpy as np A = np.array([[3, 6, 7], [5, -3, 0]]) B = np.array([[1, 1], [2, 1], [3, -3]]) C = a.dot(B) print(C) ''' Вывод: [[ 36 -12] [ -1 2]] '''

Транспонирование матрицы питон

Мы используем numpy.transpose для вычисления транспонирования матрицы.

import numpy as np A = np.array([[1, 1], [2, 1], [3, -3]]) print(A.transpose()) ''' Вывод: [[ 1 2 3] [ 1 1 -3]] '''

Как видите, NumPy значительно упростил нашу задачу.

Доступ к элементам матрицы, строкам и столбца

Доступ к элементам матрицы

Также можно получить доступ к элементам матрицы, используя индекс. Начнем с одномерного массива NumPy.

import numpy as np A = np.array([2, 4, 6, 8, 10]) print("A[0] =", A[0]) # Первый элемент print("A[2] =", A[2]) # Третий элемент print("A[-1] highlight" data-hscroll>
A [0] = 2 A [2] = 6 A [-1] = 10

Теперь выясним, как получить доступ к элементам двухмерного массива (который в основном представляет собой матрицу).

import numpy as np A = np.array([[1, 4, 5, 12], [-5, 8, 9, 0], [-6, 7, 11, 19]]) # Первый элемент первой строки print("A[0][0] =", A[0][0]) # Третий элемент второй строки print("A[1][2] =", A[1][2]) # Последний элемент последней строки print("A[-1][-1] highlight" data-hscroll>
A [0] [0] = 1 A [1] [2] = 9 A [-1] [- 1] = 19

Доступ к строкам матрицы

import numpy as np A = np.array([[1, 4, 5, 12], [-5, 8, 9, 0], [-6, 7, 11, 19]]) print("A[0] =", A[0]) # Первая строка print("A[2] =", A[2]) # Третья строка print("A[-1] highlight" data-hscroll>
A [0] = [1, 4, 5, 12] A [2] = [-6, 7, 11, 19] A [-1] = [-6, 7, 11, 19]

Доступ к столбцам матрицы

import numpy as np A = np.array([[1, 4, 5, 12], [-5, 8, 9, 0], [-6, 7, 11, 19]]) print("A[:,0] =",A[:,0]) # Первый столбец print("A[:,3] =", A[:,3]) # Четвертый столбец print("A[:,-1] highlight" data-hscroll>
A [:, 0] = [1 -5 -6] A [:, 3] = [12 0 19] A [:, - 1] = [12 0 19]

Если вы не знаете, как работает приведенный выше код, прочтите раздел "Разделение матрицы".

Разделение матрицы

Разделение одномерного массива NumPy аналогично разделению списка. Рассмотрим пример:

import numpy as np letters = np.array([1, 3, 5, 7, 9, 7, 5]) # с 3-го по 5-ый элементы print(letters[2:5]) # Вывод: [5, 7, 9] # с 1-го по 4-ый элементы print(letters[:-5]) # Вывод: [1, 3] # с 6-го до последнего элемента print(letters[5:]) # Вывод:[7, 5] # с 1-го до последнего элемента print(letters[:]) # Вывод:[1, 3, 5, 7, 9, 7, 5] # список в обратном порядке print(letters[::-1]) # Вывод:[5, 7, 9, 7, 5, 3, 1]

Теперь посмотрим, как разделить матрицу.

import numpy as np A = np.array([[1, 4, 5, 12, 14], [-5, 8, 9, 0, 17], [-6, 7, 11, 19, 21]]) print(A[:2, :4]) # две строки, четыре столбца ''' Вывод: [[ 1 4 5 12] [-5 8 9 0]] ''' print(A[:1,]) # первая строка, все столбцы ''' Вывод: [[ 1 4 5 12 14]] ''' print(A[:,2]) # все строки, второй столбец ''' Вывод: [ 5 9 11] ''' print(A[:, 2:5]) # все строки, с третьего по пятый столбец ''' Вывод: [[ 5 12 14] [ 9 0 17] [11 19 21]] '''

Использование NumPy вместо вложенных списков значительно упрощает работу с матрицами. Мы рекомендуем детально изучить пакет NumPy, если вы планируете использовать Python для анализа данных.

Вадим Дворников автор-переводчик статьи « Python Matrices and NumPy Arrays »

Пожалуйста, оставьте свои комментарии по текущей теме статьи. Мы очень благодарим вас за ваши комментарии, отклики, дизлайки, лайки, подписки!

Источник

Читайте также:  Чем открывать файлы python
Оцените статью