Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zero padding multiple values in Python

Tags:

python

numpy

In another SO, this is a solution for adding a single zero between values in a numpy.array:

import numpy as np

arr = np.arange(1, 7)                 # array([1, 2, 3, 4, 5, 6])
np.insert(arr, slice(1, None, 2), 0)  # array([1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6])

How would I add more zeros between each value in original array? For example, 5 zeros:

np.array([1, 0, 0, 0, 0, 0,
          2, 0, 0, 0, 0, 0,
          3, 0, 0, 0, 0, 0,
          4, 0, 0, 0, 0, 0,
          5, 0, 0, 0, 0, 0, 6])
like image 246
Thomas Avatar asked Jun 17 '26 06:06

Thomas


1 Answers

You can create a 2dim array, and flatten it:

import numpy as np
a = np.arange(1,7)
num_zeros = 5
z = np.zeros((a.size, num_zeros))

np.append(a[:,np.newaxis], z, axis=1)
array([[ 1.,  0.,  0.,  0.,  0.,  0.],
       [ 2.,  0.,  0.,  0.,  0.,  0.],
       [ 3.,  0.,  0.,  0.,  0.,  0.],
       [ 4.,  0.,  0.,  0.,  0.,  0.],
       [ 5.,  0.,  0.,  0.,  0.,  0.],
       [ 6.,  0.,  0.,  0.,  0.,  0.]])

np.append(a[:,np.newaxis], z, axis=1).flatten()
array([ 1.,  0.,  0.,  0.,  0.,  0.,  2.,  0.,  0.,  0.,  0.,  0.,  3.,
        0.,  0.,  0.,  0.,  0.,  4.,  0.,  0.,  0.,  0.,  0.,  5.,  0.,
        0.,  0.,  0.,  0.,  6.,  0.,  0.,  0.,  0.,  0.])

np.append(a[:,np.newaxis], z, axis=1).flatten()[:-num_zeros]
array([ 1.,  0.,  0.,  0.,  0.,  0.,  2.,  0.,  0.,  0.,  0.,  0.,  3.,
        0.,  0.,  0.,  0.,  0.,  4.,  0.,  0.,  0.,  0.,  0.,  5.,  0.,
        0.,  0.,  0.,  0.,  6.])
like image 70
shx2 Avatar answered Jun 19 '26 20:06

shx2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!