2

Is there a numpy function that pads an array this way?

import numpy as np

def pad(x, length):
    tmp = np.zeros((length,))
    tmp[:x.shape[0]] = x
    return tmp

x = np.array([1,2,3])
print pad(x, 5)

Output:

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

I couldn't find a way to do it with numpy.pad()

Yariv
  • 381
  • 3
  • 11

2 Answers2

5

You can use ndarray.resize():

>>> x = np.array([1,2,3])
>>> x.resize(5)
>>> x
array([1, 2, 3, 0, 0])

Note that this functions behaves differently from numpy.resize(), which pads with repeated copies of the array itself. (Consistency is for people who can't remember everything.)

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
3

Sven Marnach's suggestion to use ndarray.resize() is probably the simplest way to do it, but for completeness, here's how it can be done with numpy.pad:

In [13]: x
Out[13]: array([1, 2, 3])

In [14]: np.pad(x, [0, 5-x.size], mode='constant')
Out[14]: array([1, 2, 3, 0, 0])
Warren Weckesser
  • 110,654
  • 19
  • 194
  • 214