Search code examples
arraysnumpypad

How to pad a one hot array of length n with a 1 on either side of the 1


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.


Solution

  • 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])