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

Time:12-28

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.

CodePudding user response:

You can use np.pad to create two shifted copies of the array: one shifted 1 time toward the left (e.g. 0 1 0 -> 1 0 0) and one shifted 1 time toward the right (e.g. 0 1 0 -> 0 0 1).

Then you can add all three arrays together:

  0 1 0
  1 0 0
  0 0 1
-------
  1 1 1

Code:

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

Output:

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

CodePudding user response:

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