NumPy - pad() function
The NumPy pad() function is used to pad an array. This function contains an optional parameter mode, which can be used to specify string values (predefined style of padding) or a user supplied function for padding.
Syntax
numpy.pad(array, pad_width, mode='constant')
Parameters
array |
Required. Specify the array (array_like of rank N) to pad. |
pad_width |
Required. Specify {sequence, array_like, int}. It specifies number of values padded to the edges of each axis. ((before_1, after_1), … (before_N, after_N)) unique pad widths for each axis. ((before, after),) yields same before and after pad for each axis. (pad,) or int is a shortcut for before = after = pad width for all axes. |
mode |
Optional. Specify one of the following string values or a user supplied function:
|
Return Value
Returns the padded array of rank equal to array with shape increased according to pad_width.
Example:
The example below shows the usage of pad() function.
import numpy as np x = [10, 20] #padding with constant value print("Padding with constant value:") print(np.pad(x, (2,3), 'constant', constant_values=(5, 25))) #padding with edge value print("\nPadding with edge value:") print(np.pad(x, (2,3), 'edge')) #padding with maximum value print("\nPadding with maximum value:") print(np.pad(x, (2,3), 'maximum')) #padding with minimum value print("\nPadding with minimum value:") print(np.pad(x, (2,3), 'minimum')) #padding with mean value print("\nPadding with mean value:") print(np.pad(x, (2,3), 'mean')) #padding with linear_ramp value print("\nPadding with linear_ramp value:") print(np.pad(x, (2,3), 'linear_ramp', end_values=(0, 0)))
The output of the above code will be:
Padding with constant value: [ 5 5 10 20 25 25 25] Padding with edge value: [10 10 10 20 20 20 20] Padding with maximum value: [20 20 10 20 20 20 20] Padding with minimum value: [10 10 10 20 10 10 10] Padding with mean value: [15 15 10 20 15 15 15] Padding with linear_ramp value: [ 0 5 10 20 13 6 0]
Example:
Lets consider one more example where a 2-D array is padded with constant values.
import numpy as np x = [[10, 20], [30, 40]] #padding that array with 1 print("Padding with constant value:") print(np.pad(x, ((2,3),(1,2)), 'constant', constant_values=((1, 2),(3, 4))))
The output of the above code will be:
Padding with constant value: [[ 3 1 1 4 4] [ 3 1 1 4 4] [ 3 10 20 4 4] [ 3 30 40 4 4] [ 3 2 2 4 4] [ 3 2 2 4 4] [ 3 2 2 4 4]]
❮ NumPy - Functions