For example I have the following array:
[0, 0, 0, 1, 0, 0, 0]
what I want is
[0, 0, 1, 1, 1, 0, 0]
If the 1 is at the at the end, for example [1, 0, 0, 0]
it should add only on one side [1, 1, 0, 0]
How do I add a 1 on either side while keeping the array the same length? I have looked at the numpy pad function, but that didn't seem like the right approach.
One way using numpy.convolve
with mode == "same"
:
np.convolve([0, 0, 0, 1, 0, 0, 0], [1,1,1], "same")
Output:
array([0, 0, 1, 1, 1, 0, 0])
With other examples:
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])