James - 1 year ago 123

Python Question

Lets say that I have the following

`numpy array`

`[[1,1,1]`

[1,1,1]

[1,1,1]]

And I need to pad each element in the array with a zero on either side (rather then

`numpy.pad()`

`[ [0,1,0,0,1,0,0,1,0]`

[0,1,0,0,1,0,0,1,0]

[0,1,0,0,1,0,0,1,0] ]

Is there a more efficient way to do this then creating an empty array and using nested loops?

`import numpy as np`

a = np.array([[1, 2, 3],[1, 2, 3], [1, 2, 3]])

print(a)

x, y = a.shape

factor = 3

indices = np.repeat(np.arange(y + 1), 1*factor*2)[1*factor:-1*factor]

a=np.insert(a, indices, 0, axis=1)

print(a)

results in:

`[[1 2 3]`

[1 2 3]

[1 2 3]]

[[0 0 0 1 0 0 0 0 0 0 2 0 0 0 0 0 0 3 0 0 0]

[0 0 0 1 0 0 0 0 0 0 2 0 0 0 0 0 0 3 0 0 0]

[0 0 0 1 0 0 0 0 0 0 2 0 0 0 0 0 0 3 0 0 0]]

Answer Source

You can create the related indices with `np.repeat`

based on array's shape, then insert the 0 in that indices.

```
>>> def padder(arr, n):
... x, y = arr.shape
... indices = np.repeat(np.arange(y+1), n*2)[n:-n]
... return np.insert(arr, indices, 0, axis=1)
...
>>>
>>> padder(a, 1)
array([[0, 1, 0, 0, 1, 0, 0, 1, 0],
[0, 1, 0, 0, 1, 0, 0, 1, 0],
[0, 1, 0, 0, 1, 0, 0, 1, 0]])
>>>
>>> padder(a, 2)
array([[0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0]])
>>> padder(a, 3)
array([[0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]])
```

Aforementioned approach in one line:

```
np.insert(a, np.repeat(np.arange(a.shape[1] + 1), n*2)[n:-n], 0, axis=1)
```