[英]How to turn a numpy vector into a matrix, where each column in the matrix contains a range around the respective element in the initial vector?
假設我有一個 numpy 向量數組:
array([1, 2, 3])
我想將此向量轉換為一個矩陣,其中每列在初始向量中的各個元素周圍取 +/- 2 的范圍,這樣我的 output 矩陣是:
array([[-1, 0, 1],
[ 0, 1, 2],
[ 1, 2, 3],
[ 2, 3, 4],
[ 3, 4, 5]])
最好的(最好是矢量化的)方法是什么?
您可以使用以下單線來做到這一點:
result = a + np.array([-1, 0, 1])[:, np.newaxis]
(我認為,一個更優雅的解決方案)。
結果是:
array([[0, 1, 2],
[1, 2, 3],
[2, 3, 4]])
如果范圍取決於某個參數,比如rng ,你可以這樣做:
rng = 2 # From x-2 to x+2
result = a + np.arange(-rng, rng + 1)[:, np.newaxis]
得到:
array([[-1, 0, 1],
[ 0, 1, 2],
[ 1, 2, 3],
[ 2, 3, 4],
[ 3, 4, 5]])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.