![](/img/trans.png)
[英]Numpy operator for each vector element with matrix individual row multiplication
[英]Add each list element to beginning of each row in numpy matrix
我正在學習如何使用numpy矩陣函數,但遇到了問題。
我有n個整數的列表和n行的矩陣。 我需要將列表中的每個數字添加到矩陣中相應行的開頭。
因此,如果我有以下矩陣和列表:
m = np.matrix([[0, 13], [13, 0]])
myList = [10, 11]
我想要的輸出是這樣的:
newMatrix = [[10, 0, 13],
[11, 13, 0]]
這是我到目前為止的代碼(試圖復制此頁面上的最后一個示例):
for c in range(len(myList)):
newMatrix = np.insert(m[c],[0],myList[c])
但這當然只給出了for循環的最后一次迭代([11,13,0])。 我想以某種方式將每一行追加到新矩陣中,但似乎無法弄清楚。
編輯:列表和矩陣的長度將不總是已知的。
如果對numpy矩陣更有經驗的人知道更好的方法,我將不勝感激! 提前致謝。
我的解決方案是:
import numpy as np
m = np.matrix([[0, 13], [13, 0]])
myList = [10, 11]
newmatrix = np.insert(m, 0, myList, axis=1)
輸出為:
[[10 0 13]
[11 13 0]]
一種選擇是重塑myList
,然后使用np.concatenate()
函數:
import numpy as np
np.concatenate((np.array(myList).reshape(len(myList),1), m), axis = 1)
# matrix([[10, 0, 13],
# [11, 13, 0]])
您也可以這樣做:
np.concatenate((np.array(myList)[:, None], m), axis = 1)
# matrix([[10, 0, 13],
# [11, 13, 0]])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.