В тази статия ще научим за матриците на Python, използващи вложени списъци и пакета NumPy.
Матрицата е двуизмерна структура от данни, където числата са подредени в редове и колони. Например:
Тази матрица е матрица 3x4 (произнася се „три по четири“), защото има 3 реда и 4 колони.
Python Matrix
Python няма вграден тип за матрици. Можем обаче да третираме списъка със списък като матрица. Например:
A = ((1, 4, 5), (-5, 8, 9))
Можем да третираме този списък от списък като матрица с 2 реда и 3 колони.
Не забравяйте да научите за списъците на Python, преди да продължите с тази статия.
Нека да видим как да работим с вложен списък.
A = ((1, 4, 5, 12), (-5, 8, 9, 0), (-6, 7, 11, 19)) print("A =", A) print("A(1) =", A(1)) # 2nd row print("A(1)(2) =", A(1)(2)) # 3rd element of 2nd row print("A(0)(-1) =", A(0)(-1)) # Last element of 1st Row column = (); # empty list for row in A: column.append(row(2)) print("3rd column =", column)
Когато стартираме програмата, изходът ще бъде:
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 матрици, използващи вложени списъци.
- Добавете две матрици
- Транспониране на матрица
- Умножете две матрици
Използването на вложени списъци като матрица работи за прости изчислителни задачи, но има по-добър начин за работа с матрици в Python, използвайки NumPy пакет.
Масив NumPy
NumPy е пакет за научни изчисления, който има поддръжка за мощен обект с N-мерни масиви. Преди да можете да използвате NumPy, трябва да го инсталирате. За повече информация,
- Посещение: Как да инсталирам NumPy?
- Ако сте под Windows, изтеглете и инсталирайте анаконда дистрибуция на Python. Той идва с NumPy и други няколко пакета, свързани с науката за данни и машинното обучение.
След като NumPy бъде инсталиран, можете да го импортирате и използвате.
NumPy предоставя многоизмерен масив от числа (който всъщност е обект). Да вземем пример:
import numpy as np a = np.array((1, 2, 3)) print(a) # Output: (1, 2, 3) print(type(a)) # Output:
Както можете да видите, се извиква класът на масива на NumPy ndarray
.
Как да създам масив NumPy?
Има няколко начина за създаване на масиви NumPy.
1. Масив от цели числа, плувки и комплексни числа
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))) # Array of floats print(A) A = np.array(((1, 2, 3), (3, 4, 5)), dtype = complex) # Array of complex numbers 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))
2. Масив от нули и единици
import numpy as np zeors_array = np.zeros( (2, 3) ) print(zeors_array) ''' Output: ((0. 0. 0.) (0. 0. 0.)) ''' ones_array = np.ones( (1, 5), dtype=np.int32 ) // specifying dtype print(ones_array) # Output: ((1 1 1 1 1))
Тук сме посочили dtype
32 бита (4 байта). Следователно този масив може да приема стойности от до .-2-31
2-31-1
3. Използване на arange () и shape ()
import numpy as np A = np.arange(4) print('A =', A) B = np.arange(12).reshape(2, 6) print('B =', B) ''' Output: A = (0 1 2 3) B = (( 0 1 2 3 4 5) ( 6 7 8 9 10 11)) '''
Learn more about other ways of creating a NumPy array.
Matrix Operations
Above, we gave you 3 examples: addition of two matrices, multiplication of two matrices and transpose of a matrix. We used nested lists before to write those programs. Let's see how we can do the same task using NumPy array.
Addition of Two Matrices
We use +
operator to add corresponding elements of two NumPy matrices.
import numpy as np A = np.array(((2, 4), (5, -6))) B = np.array(((9, -3), (3, 6))) C = A + B # element wise addition print(C) ''' Output: ((11 1) ( 8 0)) '''
Multiplication of Two Matrices
To multiply two matrices, we use dot()
method. Learn more about how numpy.dot works.
Note: *
is used for array multiplication (multiplication of corresponding elements of two arrays) not matrix multiplication.
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) ''' Output: (( 36 -12) ( -1 2)) '''
Transpose of a Matrix
We use numpy.transpose to compute transpose of a matrix.
import numpy as np A = np.array(((1, 1), (2, 1), (3, -3))) print(A.transpose()) ''' Output: (( 1 2 3) ( 1 1 -3)) '''
As you can see, NumPy made our task much easier.
Access matrix elements, rows and columns
Access matrix elements
Similar like lists, we can access matrix elements using index. Let's start with a one-dimensional NumPy array.
import numpy as np A = np.array((2, 4, 6, 8, 10)) print("A(0) =", A(0)) # First element print("A(2) =", A(2)) # Third element print("A(-1) =", A(-1)) # Last element
When you run the program, the output will be:
A(0) = 2 A(2) = 6 A(-1) = 10
Now, let's see how we can access elements of a two-dimensional array (which is basically a matrix).
import numpy as np A = np.array(((1, 4, 5, 12), (-5, 8, 9, 0), (-6, 7, 11, 19))) # First element of first row print("A(0)(0) =", A(0)(0)) # Third element of second row print("A(1)(2) =", A(1)(2)) # Last element of last row print("A(-1)(-1) =", A(-1)(-1))
When we run the program, the output will be:
A(0)(0) = 1 A(1)(2) = 9 A(-1)(-1) = 19
Access rows of a Matrix
import numpy as np A = np.array(((1, 4, 5, 12), (-5, 8, 9, 0), (-6, 7, 11, 19))) print("A(0) =", A(0)) # First Row print("A(2) =", A(2)) # Third Row print("A(-1) =", A(-1)) # Last Row (3rd row in this case)
When we run the program, the output will be:
A(0) = (1, 4, 5, 12) A(2) = (-6, 7, 11, 19) A(-1) = (-6, 7, 11, 19)
Access columns of a Matrix
import numpy as np A = np.array(((1, 4, 5, 12), (-5, 8, 9, 0), (-6, 7, 11, 19))) print("A(:,0) =",A(:,0)) # First Column print("A(:,3) =", A(:,3)) # Fourth Column print("A(:,-1) =", A(:,-1)) # Last Column (4th column in this case)
When we run the program, the output will be:
A(:,0) = ( 1 -5 -6) A(:,3) = (12 0 19) A(:,-1) = (12 0 19)
If you don't know how this above code works, read slicing of a matrix section of this article.
Slicing of a Matrix
Slicing of a one-dimensional NumPy array is similar to a list. If you don't know how slicing for a list works, visit Understanding Python's slice notation.
Да вземем пример:
import numpy as np letters = np.array((1, 3, 5, 7, 9, 7, 5)) # 3rd to 5th elements print(letters(2:5)) # Output: (5, 7, 9) # 1st to 4th elements print(letters(:-5)) # Output: (1, 3) # 6th to last elements print(letters(5:)) # Output:(7, 5) # 1st to last elements print(letters(:)) # Output:(1, 3, 5, 7, 9, 7, 5) # reversing a list print(letters(::-1)) # Output:(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)) # two rows, four columns ''' Output: (( 1 4 5 12) (-5 8 9 0)) ''' print(A(:1,)) # first row, all columns ''' Output: (( 1 4 5 12 14)) ''' print(A(:,2)) # all rows, second column ''' Output: ( 5 9 11) ''' print(A(:, 2:5)) # all rows, third to the fifth column '''Output: (( 5 12 14) ( 9 0 17) (11 19 21)) '''
Както можете да видите, използването на NumPy (вместо вложени списъци) улеснява много работата с матрици и дори не сме надраскали основите. Предлагаме ви да проучите подробно пакета NumPy, особено ако се опитвате да използвате Python за наука за данни / анализ.
Ресурси на NumPy, които бихте могли да намерите за полезни:
- Урок за NumPy
- Референция за NumPy