比方說,我有一個2D NumPy的ndarray,就像這樣:如何有效地將矩陣變換應用於NumPy數組的每一行?
[[ 0, 1, 2, 3 ],
[ 4, 5, 6, 7 ],
[ 8, 9, 10, 11 ]]
從概念上來講,我想要做的是這樣的:
For each row:
Transpose the row
Multiply the transposed row by a transformation matrix
Transpose the result
Store the result in the original ndarray, overwriting the original row data
我有一個極其緩慢,蠻力方法在功能上實現這一點:
import numpy as np
transform_matrix = np.matrix(/* 4x4 matrix setup clipped for brevity */)
for i, row in enumerate(data):
tr = row.reshape((4, 1))
new_row = np.dot(transform_matrix, tr)
data[i] = new_row.reshape((1, 4))
但是,這似乎是NumPy應該做的那種操作w第i個。我假設 - 作爲NumPy的新手 - 我只是在文檔中缺少一些基本的東西。任何指針?
請注意,如果創建新的ndarray比創建新的ndarray更快,而不是就地編輯它,那也適用於我正在做的事情;主要關心的是手術的速度。
切片是多餘這裏,我想 – alko
完善!感謝您也通讀了解釋 - 這非常有幫助。 – user3089880