NumPy pad()

The pad() method adds a specified value around the array axis to achieve a desired length.

Example

import numpy as np

# create a 2D array
array = np.array([[1, 2],
                  [3, 4]])

# pad the array with zeros padded_array = np.pad(array, pad_width=1)
print(padded_array) ''' Output: [[0 0 0 0] [0 1 2 0] [0 3 4 0] [0 0 0 0]] '''

pad() Syntax

The syntax of pad() is:

numpy.pad(array, pad_width, mode = 'constant', **kwargs)

pad() Arguments

The pad() method takes multiple arguments:

  • array - array to pad
  • pad_width - number of values to pad on each axis
  • mode(optional) - determines how the values are padded
  • **kwargs(optional) - additional keyword arguments that can be used

pad() Return Value

The pad() method returns a new array with padded values on the borders of the original array.


Pad a 2-D Array

import numpy as np

# create a 2D array
array = np.array([[1, 2],
                  [3, 4]])

# pad the array with one zero on all sides padded_array = np.pad(array, pad_width=1)
print('Array padded by width 1 on all sides:\n', padded_array)
# pad the array with one zero before and 2 zeros after the original array, # one zero on top and left and two zeros on the right and bottom sides padded_array = np.pad(array, pad_width=(1, 2))
print('Array padded by width (1,2):\n', padded_array)
# pad the array with zeros using different widths for each axis # (1, 2) on top and bottom, (2, 1) on left and right padded_array = np.pad(array, pad_width=((1, 2), (2, 1)))
print('Array padded by width (1,2), (2,1):\n', padded_array)

Output

Array padded by width 1 on all sides:
[[0 0 0 0]
 [0 1 2 0]
 [0 3 4 0]
 [0 0 0 0]]
Array padded by width (1,2):
[[0 0 0 0 0]
 [0 1 2 0 0]
 [0 3 4 0 0]
 [0 0 0 0 0]
 [0 0 0 0 0]]
Array padded by width (1,2), (2,1):
 [[0 0 0 0 0]
 [0 0 1 2 0]
 [0 0 3 4 0]
 [0 0 0 0 0]
 [0 0 0 0 0]]

Mode Argument in pad()

The mode is an optional argument in pad() that specifies the pattern in which the array elements are padded.

The mode can be:

  • 'constant': pads with a constant value
  • 'edge': pads with the nearest edge value
  • 'linear_ramp': pads with a linear ramp between the edge value and the end value
  • 'maximum': pads with the maximum value of the input array
  • 'mean': pads with the mean value of the input array
  • 'median': pads with the median value of the input array
  • 'minimum': pads with the minimum value of the input array
  • 'reflect': pads by mirroring the values of the array
  • 'symmetric': pads by mirroring the values, including the boundary values
  • 'wrap': pads with a circular wrap of the array
  • 'empty': pads with undefined values

The **kwargs parameter allows you to pass additional keyword arguments specific to the chosen padding mode. Different modes have different optional arguments specified by **kwargs to customize their behavior.


Example 1: Padding With 'constant' Mode

In numpy.pad(), we can use the 'constant' mode to set the padding value. It takes an additional argument constant_values.

Let's look at an example.

import numpy as np

# create a 1-D array
array1 = np.array([1, 2, 3, 4])

# pad an array with a constant value -1 array2 = np.pad(array1, pad_width = 1, mode = 'constant', constant_values = -1)
print(array2)

Output

[-1  1  2  3  4 -1]

Notes:

  • 'constant' is the default mode.
  • If constant_values is not specified, 0 is used by default.

Example 2: Padding With 'edge' Mode

In numpy.pad(), 'edge' mode extends the values at the edges of the array outward.

import numpy as np

# create an 1D array
array1 = np.array([1, 2, 3, 4])

# pad array with edge values array2 = np.pad(array1, pad_width = 1, mode = 'edge')
print(array2)

Output

[1 1 2 3 4 4]

Example 3: Padding With 'linear_ramp' Mode

In numpy.pad(), 'linear_ramp' specifies the starting and ending padding values. It supports one additional argument end_values.

import numpy as np

# create a 1D array
array1 = np.array([1, 2, 3, 4])

# pad the array by applying linear_ramp from 4 to -1 on both sides array2 = np.pad(array1, pad_width = 1, mode = 'linear_ramp', end_values = (4, -1))
print("Array padded with linear ramp:\n", array2)
# pad the array with wider padding and the same linear ramp array3 = np.pad(array1, pad_width = 2, mode='linear_ramp', end_values = (4, -1))
print("Array padded with linear ramp and wider padding:\n", array3)

Output

Array padded with linear ramp:
[ 4  1  2  3  4 -1]
Array padded with linear ramp and wider padding:
 [ 4  2  1  2  3  4  1 -1]

Note: The linear_ramp mode requires the specified end_values to have the same dtype as the array.


Example 4: Padding With 'maximum' and 'minimum' Mode

In numpy.pad(), 'maximum' mode pads the input array with the maximum value of the input array whereas 'minimum' mode pads with the minimum value. They support one additional argument stat_length.

stat_length specifies the number of values at the edge of each axis used to calculate the statistic value. It is None by default and uses the entire array.

import numpy as np

# create a 1-D array
array1 = np.array([1, 2, 3, 4])

# pad the array with the maximum value from the array array2 = np.pad(array1, pad_width = 1, mode = 'maximum')
print(array2) # [4 1 2 3 4 4]
# pad the array with the minimum value from the array array3 = np.pad(array1, pad_width = 1, mode = 'minimum')
print(array3) # [1 1 2 3 4 1]
# pad the array with the maximum value from two adjacent edge values array4 = np.pad(array1, pad_width = 1, mode = 'maximum',stat_length = 2)
print(array4) # [2 1 2 3 4 4]
# pad array with the minimum value from two adjacent edge values array5 = np.pad(array1, pad_width = 1, mode = 'minimum',stat_length = 2)
print(array5) # [1 1 2 3 4 3]

Example 5: Padding With 'mean' and 'median' Mode

In numpy.pad(), 'mean' mode pads the input array with the mean value of the input array whereas 'median' mode pads the input array with the median value of the input array. They support one additional argument stat_length.

stat_length specifies the number of values at the edge of each axis used to calculate the statistic value. It is None by default and uses the entire array.

import numpy as np

# create an 1D array
array1 = np.array([1, 3, 5, 9, 11])

# pad array with the mean value from the whole array array2 = np.pad(array1, pad_width = 1, mode = 'mean')
print(array2) # [ 6 1 3 5 9 11 6]
# pad array with the median value from the whole array array3 = np.pad(array1, pad_width = 1, mode = 'median')
print(array3) # [ 5 1 3 5 9 11 5]
# pad array with the mean value from 3 adjacent edge values array4 = np.pad(array1, pad_width = 1, mode = 'mean',stat_length = 3)
print(array4) # [ 3 1 3 5 9 11 8]
# pad array with the median value from 3 adjacent edge values array5 = np.pad(array1, pad_width = 1, mode = 'median',stat_length = 3)
print(array5) # [ 3 1 3 5 9 11 9]

Example 6: Padding With reflect and symmetric mode

In numpy.pad(), 'reflect' mode pads the input array by mirroring the values of the array, and 'symmetric' mode pads by mirroring the values of the array including the boundary values.

They support one additional argument reflect_type.

reflect_type can be even or odd:

  • even (default): padding is done by using the mirrored value
  • odd: padding is mirrored is done by using 2 * edge value - mirrored value
import numpy as np

# create a 1D array
array1 = np.array([1, 3, 5, 9, 11])

# pad the array using reflect mode and even reflect_type array2 = np.pad(array1, pad_width=2, mode='reflect') # pad the array using reflect mode and odd reflect_type array3 = np.pad(array1, pad_width=2, mode='reflect', reflect_type='odd') # pad the array using symmetric mode and even reflect_type array4 = np.pad(array1, pad_width=2, mode='symmetric', reflect_type='even') # pad the array using symmetric mode and odd reflect_type array5 = np.pad(array1, pad_width=2, mode='symmetric', reflect_type='odd')
print("Array padded with reflect mode and even reflect_type:\n", array2) print("Array padded with reflect mode and odd reflect_type:\n", array3) print("Array padded with symmetric mode and even reflect_type:\n", array4) print("Array padded with symmetric mode and odd reflect_type:\n", array5)

Output

Array padded with reflect mode and even reflect_type:
[ 5  3  1  3  5  9 11  9  5]
Array padded with reflect mode and odd reflect_type:
[-3 -1  1  3  5  9 11 13 17]
Array padded with symmetric mode and even reflect_type:
[ 3  1  1  3  5  9 11 11  9]
Array padded with symmetric mode and odd reflect_type:
[-1  1  1  3  5  9 11 11 13]

Example 7: Padding With 'wrap' mode

In numpy.pad(), 'wrap' mode pads the array with a circular wrap of the array. It supports no additional arguments.

import numpy as np

# create a 1D array
array1 = np.array([1, 2, 3, 4])

# pad the array using wrap mode, which wraps the array values around cyclically array2 = np.pad(array1, pad_width=1, mode='wrap') # pad the array with wider padding using wrap mode array3 = np.pad(array1, pad_width=2, mode='wrap')
print("Array padded with wrap mode:\n", array2) print("Array padded with wrap mode and wider padding:\n", array3)

Output

Array padded with wrap mode:
[4 1 2 3 4 1]
Array padded with wrap mode and wider padding:
 [3 4 1 2 3 4 1 2]

Example 8: Padding With 'empty' mode

In numpy.pad(), 'empty' mode pads the input array using uninitialized values. It supports no additional arguments.

import numpy as np

# create a 1D array
array1 = np.array([1, 2, 3, 4])

# pad the array using empty mode, which pads with empty values array2 = np.pad(array1, pad_width=1, mode='empty')
print("Array padded with empty mode:\n", array2)

Output

Array padded with empty mode:
[              4253                  1                  2                  3                  4 723435939191610164]

Note: The numbers used for padding are not random, they are uninitialized/garbage values.


Using Custom Padding Function as mode

You can define a custom padding function to pad an array. It has the following signature:

padding_func(vector, iaxis_pad_width, iaxis, kwargs)

where

  • vector: a rank 1 array already padded with zeros
  • iaxis_pad_width: a tuple with 2 elements
    • iaxis_pad_width[0] is the number of values padded at the beginning of vector
    • iaxis_pad_width[1] is the number of values padded at the end of vector
  • iaxis : axis currently being calculated
  • kwargs: any keyword arguments that the function requires

For example,

import numpy as np

# custom padding function def custom_padding(arr, pad_width, iaxis,kwargs): #pad with 2 before the array arr[:pad_width[0]] = 2 #pad with 3 after the array arr[-pad_width[1]:] = 3
# create a 1D array array1 = np.array([1, 2, 3, 4])
# pad the array using the custom padding function as the mode padded_array = np.pad(array1, 2, custom_padding)
print("Original Array:\n", array1) print("Padded Array using Custom Padding Function as Mode:\n", padded_array)

Output

Original Array:
[1 2 3 4]
Padded Array using Custom Padding Function as Mode:
 [2 2 1 2 3 4 3 3]