在此问题中,我们将分别找到所有行和所有列的总和。我们将使用该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()