如何利用 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() 函式僅考慮列。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP