如何利用 Numpy 求出一个给定矩阵的行和和列和?


在这个问题中,我们将分别求出所有行的和和所有列的和。我们将使用 sum() 函数来获取和。

算法

Step 1: Import numpy.
Step 2: Create a numpy matrix of mxn dimension.
Step 3: Obtain the sum of all the rows.
Step 4: Obtain the sum of all the columns.

示例代码

import numpy as np

a = np.matrix('10 20; 30 40')
print("Our matrix: \n", a)

sum_of_rows = np.sum(a, axis = 0)
print("\nSum of all the rows: ", sum_of_rows)

sum_of_cols = np.sum(a, axis = 1)
print("\nSum of all the columns: \n", sum_of_cols)

输出

Our matrix:
 [[10 20]
 [30 40]]
Sum of all the rows:  [[40 60]]
Sum of all the columns:
 [[30]
 [70]]

解释

np.sum() 函数接受一个称为“axis”的附加矩阵。Axis 取两个值。为 0 或 1。如果 axis=0,它告诉 sum() 函数仅考虑行。如果 axis = 1,它告诉 sum() 函数仅考虑列。

更新时间:2021 年 3 月 16 日

3K+ 查看次数

启动您的 职业

通过完成课程获得认证

开始
广告
© . All rights reserved.