例如我有以下陣列:
[0, 0, 0, 1, 0, 0, 0]
我想要的是
[0, 0, 1, 1, 1, 0, 0]
如果 1 在最后,例如[1, 0, 0, 0]它應該只在一側添加[1, 1, 0, 0]
如何在保持陣列長度相同的同時在任一側添加 1?我看過 numpy pad 功能,但這似乎不是正確的方法。
uj5u.com熱心網友回復:
使用numpy.convolvewith 的一種方式mode == "same":
np.convolve([0, 0, 0, 1, 0, 0, 0], [1,1,1], "same")
輸出:
array([0, 0, 1, 1, 1, 0, 0])
與其他示例:
np.convolve([1,0,0,0], [1,1,1], "same")
# array([1, 1, 0, 0])
np.convolve([0,0,0,1], [1,1,1], "same")
# array([0, 0, 1, 1])
np.convolve([1,0,0,0,1,0,0,0], [1,1,1], "same")
# array([1, 1, 0, 1, 1, 1, 0, 0])
uj5u.com熱心網友回復:
您可以使用np.pad創建陣列的兩個移位副本:一個向左移動 1 次(例如0 1 0-> 1 0 0),另一個向右移動 1 次(例如0 1 0-> 0 0 1)。
然后您可以將所有三個陣列相加:
0 1 0
1 0 0
0 0 1
-------
1 1 1
代碼:
output = a np.pad(a, (1,0))[:-1] np.pad(a, (0,1))[1:]
# (1, 0) says to pad 1 time at the start of the array and 0 times at the end
# (0, 1) says to pad 0 times at the start of the array and 1 time at the end
輸出:
# Original array
>>> a = np.array([1, 0, 0, 0, 1, 0, 0, 0])
>>> a
array([1, 0, 0, 0, 1, 0, 0, 0])
# New array
>>> output = a np.pad(a, (1,0))[:-1] np.pad(a, (0,1))[1:]
>>> output
array([1, 1, 0, 1, 1, 1, 0, 0])
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/396611.html
