2

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.

2 Answers2

1

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])
  • 1
    Thanks! This is an interesting technique, I think the convolve solution would be preferable in terms of code legibility, but this too is very helpful! – Dr Acme Isme Dec 28 '21 at 11:51
1

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])
Chris
  • 29,127
  • 3
  • 28
  • 51