Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zero pad numpy array

What's the more pythonic way to pad an array with zeros at the end?

def pad(A, length):     ...  A = np.array([1,2,3,4,5]) pad(A, 8)    # expected : [1,2,3,4,5,0,0,0] 

In my real use case, in fact I want to pad an array to the closest multiple of 1024. Ex: 1342 => 2048, 3000 => 3072

like image 548
Basj Avatar asked Jul 04 '16 20:07

Basj


People also ask

How do I pad a NumPy array in Python?

pad() function is used to pad the Numpy arrays. Sometimes there is a need to perform padding in Numpy arrays, then numPy. pad() function is used. The function returns the padded array of rank equal to the given array and the shape will increase according to pad_width.

How do you add zeros to the end of a NumPy array?

You can use numpy. pad , which pads default 0 to both ends of the array while in constant mode, specify the pad_width = (0, N) will pad N zeros to the right and nothing to the left: N = 4 np.

What is padding an array?

The array padding transformation sets a dimension in an array to a new size. The goal of this transformation is to reduce the number of memory system conflicts. The transformation is applied to a full function AST. The new size can be specified by the user or can be computed automatically.

Are NumPy arrays zero indexed?

Access Array Elements You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.


1 Answers

numpy.pad with constant mode does what you need, where we can pass a tuple as second argument to tell how many zeros to pad on each size, a (2, 3) for instance will pad 2 zeros on the left side and 3 zeros on the right side:

Given A as:

A = np.array([1,2,3,4,5])  np.pad(A, (2, 3), 'constant') # array([0, 0, 1, 2, 3, 4, 5, 0, 0, 0]) 

It's also possible to pad a 2D numpy arrays by passing a tuple of tuples as padding width, which takes the format of ((top, bottom), (left, right)):

A = np.array([[1,2],[3,4]])  np.pad(A, ((1,2),(2,1)), 'constant')  #array([[0, 0, 0, 0, 0],           # 1 zero padded to the top #       [0, 0, 1, 2, 0],           # 2 zeros padded to the bottom #       [0, 0, 3, 4, 0],           # 2 zeros padded to the left #       [0, 0, 0, 0, 0],           # 1 zero padded to the right #       [0, 0, 0, 0, 0]]) 

For your case, you specify the left side to be zero and right side pad calculated from a modular division:

B = np.pad(A, (0, 1024 - len(A)%1024), 'constant') B # array([1, 2, 3, ..., 0, 0, 0]) len(B) # 1024 

For a larger A:

A = np.ones(3000) B = np.pad(A, (0, 1024 - len(A)%1024), 'constant') B # array([ 1.,  1.,  1., ...,  0.,  0.,  0.])  len(B) # 3072 
like image 67
Psidom Avatar answered Sep 27 '22 21:09

Psidom