Skip to content
Related Articles

Related Articles

numpy.pad() function in Python

Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 01 Oct, 2020
Improve Article
Save Article

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 :

  • array: the array to pad
  • pad_width: This parameter defines the number of values that are padded to the edges of each axis.
    mode : str or function(optional)
  • **kwargs: allows you to pass keyword variable length of argument to a function. It is used when we want to handle the named argument in a function.

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

Example 1:

Python3




# Python program to explain
# working of numpy.pad() function
import numpy as np
  
  
arr = [1, 3, 2, 5, 4]
  
# padding array using CONSTANT mode
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




# Python program to explain
# working of numpy.pad() function
import numpy as np
  
  
arr = [1, 3, 2, 5, 4
  
# padding array using 'linear_ramp' mode
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




# Python program to explain
# working of numpy.pad() function
import numpy as np
  
  
arr = [1, 3, 9, 5, 4]
  
# padding array using 'maximum' mode
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




# Python program to explain
# working of numpy.pad() function
import numpy as np
  
  
arr = [[1, 3],[5, 8]] 
  
# padding array using 'minimum' mode
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]]

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!