Python 中的矩阵操作


我们可以使用 Numpy 库轻松地在 Python 中执行矩阵操作。NumPy 是一个 Python 包。它代表“数值 Python”。它是一个由多维数组对象和一系列用于处理数组的例程组成的库。使用 NumPy,可以对数组执行数学和逻辑运算。

安装和导入 Numpy

要安装 Numpy,请使用 pip −

pip install numpy

导入 Numpy −

import numpy

加、减、乘、除矩阵

我们将使用以下 Numpy 方法来进行矩阵操作 −

  • numpy.add() − 加两个矩阵

  • numpy.subtract() − 减去两个矩阵

  • numpy.divide() − 除以两个矩阵

  • numpy.multiply() − 乘以两个矩阵

我们现在来看看代码 −

示例

Open Compiler
import numpy as np # Two matrices mx1 = np.array([[5, 10], [15, 20]]) mx2 = np.array([[25, 30], [35, 40]]) print("Matrix1 =\n",mx1) print("\nMatrix2 =\n",mx2) # The addition() is used to add matrices print ("\nAddition of two matrices: ") print (np.add(mx1,mx2)) # The subtract() is used to subtract matrices print ("\nSubtraction of two matrices: ") print (np.subtract(mx1,mx2)) # The divide() is used to divide matrices print ("\nMatrix Division: ") print (np.divide(mx1,mx2)) # The multiply()is used to multiply matrices print ("\nMultiplication of two matrices: ") print (np.multiply(mx1,mx2))

输出

Matrix1 =
 [[ 5 10]
 [15 20]]

Matrix2 =
[[25 30]
 [35 40]]

Addition of two matrices:
[[30 40]
 [50 60]]

Subtraction of two matrices:
[[-20 -20]
 [-20 -20]]

Matrix Division:
[[0.2 0.33333333]
 [0.42857143 0.5 ]]

Multiplication of two matrices:
[[125 300]
 [525 800]]

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

矩阵元素求和

使用 sum() 方法来求和 −

示例

Open Compiler
import numpy as np # A matrix mx = np.array([[5, 10], [15, 20]]) print("Matrix =\n",mx) print ("\nThe summation of elements=") print (np.sum(mx)) print ("\nThe column wise summation=") print (np.sum(mx,axis=0)) print ("\nThe row wise summation=") print (np.sum(mx,axis=1))

输出

Matrix =
 [[ 5 10]
 [15 20]]

The summation of elements=
50

The column wise summation=
[20 30]

The row wise summation=
[15 35]

转置矩阵

使用 .T 属性来求矩阵的转置 −

示例

Open Compiler
import numpy as np # A matrix mx = np.array([[5, 10], [15, 20]]) print("Matrix =\n",mx) print ("\nThe Transpose =") print (mx.T)

输出

Matrix =
 [[ 5 10]
 [15 20]]

The Transpose =
[[ 5 15]
 [10 20]]

更新于: 2022 年 8 月 11 日

15K+ 次查看

开启您的 职业生涯

完成课程并获得认证

开始
广告