English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutorial di base di Python

Controllo dei flussi Python

Funzione in Python

Tipi di dati in Python

Operazioni su file Python

Oggetti e classi Python

Data e ora Python

Conoscenze avanzate di Python

Manuale di Python

Python 矩阵和NumPy数组

In questo articolo impareremo a utilizzare liste annidate e il pacchetto NumPy per le matrici Python.

Una matrice è una struttura dati bidimensionale in cui i numeri sono disposti per righe e colonne. Ad esempio:

Questa matrice è una matrice 3x4 ("tre per quattro") perché ha 3 righe e 4 colonne.

Matrice Python

Python non ha un tipo di matrice integrato. Ma possiamo considerare liste di liste come matrici. Ad esempio:

A = [[1, 4, 5], 
    [-5, 8, 9]]

Possiamo considerare questa lista di liste come una matrice con 2 righe e 3 colonne.

Prima di continuare con questo articolo, è necessario comprendereLista Python

Vediamo come utilizzare liste annidate.

A = [[1, 4, 5, 12], 
    [-5, 8, 9, 0],
    [-6, 7, 11, 19]]
print("A =", A) 
print("A[1] =", A[1])      # seconda riga
print("A[1][2] =", A[1][2])   # terzo elemento della seconda riga
print("A[0][-1] =", A[0][-1])   # ultimo elemento della prima riga
column = [];        # lista vuota
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
3rd column = [5, 9, 11]

Ecco alcuni esempi di matrici Python correlate all'uso di liste annidate.

L'uso di liste annidate come matrici può essere utile per compiti di calcolo semplici, ma l'usoNumPyIl pacchetto di Python è un metodo migliore per gestire le matrici.

Matrice NumPy

NumPy是用于科学计算的软件包,它支持强大的N维数组对象。在使用NumPy之前,您需要先安装它。有关更多信息,

一旦安装了NumPy,就可以导入和使用它。

NumPy提供数字的多维数组(实际上是一个对象)。让我们举个实例:

import numpy as np
a = np.array([1, 2, 3])
print(a) # 输出: [1, 2, 3]
print(type(a)) # 输出: <class 'numpy.ndarray'>

正如您看到的,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]]) # 浮点数组
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]

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) // dtype
print(ones_array) # 输出: [[1 1 1 1 1]]

在这里,我们指定dtype为32位(4字节)。因此,该数组可以采用从到的值。-2-312-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]
'''

了解有关创建NumPy数组的其他方法的更多信息。

矩阵运算

上面,我们为您提供了3个示例:两个矩阵相加,两个矩阵相乘以及一个矩阵转置。在编写这些程序之前,我们使用了嵌套列表。让我们看看如何使用NumPy数组完成相同的任务。

两种矩阵的加法

我们使用+运算符将两个NumPy矩阵的对应元素相加。

import numpy as np
A = np.array([[2, 4], [5, -6]])
B = np.array([[9, -3], [3, 6]])
C = A + B  # 元素聪明的加法
print(C)
''' 
Output:
[[11  1]
 [ 8  0]
 '''

两个矩阵相乘

为了将两个矩阵相乘,我们使用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)
''' 
Output:
[[ 36 -12]
 [ -1  2]
'''

矩阵转置

我们使用numpy.transpose计算矩阵的转置。

import numpy as np
A = np.array([[1, 1], [2, 1], [3, -3]])
print(A.transpose())
''' 
Output:
[[ 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] =", A[-1])  # 最后一个元素

运行该程序时,输出为:

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]])
#  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])

当我们运行程序时,输出将是:

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]) # First Row
print("A[2] =", A[2]) # Third Row
print("A[-1] =", A[-1]) # Last Row (3rd row in this case)

当我们运行程序时,输出将是:

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]) # First Column
print("A[:,3] =", A[:,3]) # Fourth Column
print("A[:,-1] =", A[:,-1]) # Last Column (4th column in this case)

当我们运行程序时,输出将是:

A[:,0] = [ 1 -5 -6]
A[:,3] = [12  0 19]
A[:,-1] = [12  0 19]

如果您不知道上面的代码如何工作,请阅读本文矩阵部分的切片。

矩阵切片

一维NumPy数组的切片类似于列表。如果您不知道列表切片的工作原理,请访问了解Python的切片符号

让我们举个实例:

import numpy as np
letters = np.array([1, 3, 5, 7, 9, 7, 5])
# 3rd to 5th elements
print(letters[2:5])        # 输出: [5, 7, 9]
# 1st to 4th elements
print(letters[:-5])         # 输出: [1, 3]   
# 6th to last elements
print(letters[5:])          # 输出:[7, 5]
# 1st to last elements
print(letters[:])           # 输出:[1, 3, 5, 7, 9, 7, 5]
# reversing a list
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])  # 两行,四列
''' Output:
[[ 1 4 5 12]]
 [-5 8 9 0]]
'''
print(A[:1,])  # 第一行,所有列
''' Output:
[[ 1 4 5 12 14]]
'''
print(A[:,2])  # 所有的行,第二列
''' Output:
[ 5 9 11]
'''
print(A[:, 2:5])  #所有的行,第三到第五列
'''Output:
[[ 5 12 14]
 [ 9 0 17]
 [11 19 21]]
'''

正如您所看到的,使用NumPy(而不是嵌套列表)可以更轻松地处理矩阵,而且我们甚至都没有涉及基础知识。我们建议您详细研究NumPy软件包,尤其是当您尝试将Python用于数据科学/分析时。

NumPy资源,您可能会发现有帮助: