numpy.pad() function in Python (original) (raw)

Last Updated : 01 Oct, 2020

numpy.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.

Syntax: numpy.pad(array, pad_width, mode=’constant’, **kwargs)

Parameters :

Return:
A padded array of rank equal to an array with shape increased according to pad_width.

Example 1:

Python3

import numpy as np

arr = [ 1 , 3 , 2 , 5 , 4 ]

pad_arr = np.pad(arr, ( 3 , 2 ), 'constant' ,

`` constant_values = ( 6 , 4 ))

print (pad_arr)

Output:

[6 6 6 1 3 2 5 4 4 4]

Example 2:

Python3

import numpy as np

arr = [ 1 , 3 , 2 , 5 , 4 ]

pad_arr = np.pad(arr, ( 3 , 2 ), 'linear_ramp' ,

`` end_values = ( - 4 , 5 ))

print (pad_arr)

Output:

[-4 -2 -1 1 3 2 5 4 4 5]

Example 3:

Python3

import numpy as np

arr = [ 1 , 3 , 9 , 5 , 4 ]

pad_arr = np.pad(arr, ( 3 ,), 'maximum' )

print (pad_arr)

Output:

[9 9 9 1 3 9 5 4 9 9 9]

Example 4:

Python3

import numpy as np

arr = [[ 1 , 3 ],[ 5 , 8 ]]

pad_arr = np.pad(arr, ( 3 ,), 'minimum' )

print (pad_arr)

Output:

[[1 1 1 1 3 1 1 1] [1 1 1 1 3 1 1 1] [1 1 1 1 3 1 1 1] [1 1 1 1 3 1 1 1] [5 5 5 5 8 5 5 5] [1 1 1 1 3 1 1 1] [1 1 1 1 3 1 1 1] [1 1 1 1 3 1 1 1]]

Similar Reads