如何使用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 好听的元旦简短祝福语