本文介紹了通過使用 NumPy 對 2 個數(shù)組元素數(shù)組進行求和來形成矩陣的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
假設(shè)我有以下 NumPy 數(shù)組:
Let's say I have the following NumPy arrays:
i = array([2, 4, 5])
j = array([0, 1, 2])
我希望有一個非常有效的方法(如果可能,內(nèi)置)來對這些向量求和,并得到如下所示的輸出:
I would like to have a very efficient method (built-in if possible) to sum those vectors and have an output that looks like this:
[[2 4 5]
[3 5 6]
[4 6 7]]
所以基本上每一列都是數(shù)組 j,其中 i 的第 k 個元素已添加到其中(在本例中為 k = 0, 1, 2)
So basically each column is the array j to which the k th element of i has been added (k = 0, 1, 2 in this case)
推薦答案
使用 numpy.add.outer
.
>>> import numpy as np
>>> i = np.array([2, 4, 5])
>>> j = np.array([0, 1, 2])
>>>
>>> np.add.outer(j, i)
array([[2, 4, 5],
[3, 5, 6],
[4, 6, 7]])
這篇關(guān)于通過使用 NumPy 對 2 個數(shù)組元素數(shù)組進行求和來形成矩陣的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!