如何使用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()
热门推荐
10 祝孙辈生日祝福语简短
11 恋人跨年祝福语大全简短
12 考大学敬酒简短祝福语
13 开工投产大吉祝福语 简短
14 偶然结婚祝福语朋友简短
15 感谢学长学姐祝福语简短
16 戏精的祝福语简短
17 我要结婚祝福语简短
18 婚前女儿生日祝福语简短