如何使用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]]
解释
该函数采用一个称为“轴”的附加矩阵。轴取两个值。0或1。如果axis = 0,它告诉函数仅考虑行。如果axis = 1,则告诉函数仅考虑列。np.sum()sum()sum()
以上是 如何使用Numpy查找给定矩阵的行和列的总和? 的全部内容, 来源链接: utcz.com/z/317506.html