Python中的 numpy.pad()函数
numpy.pad()函数用于填充 Numpy 数组。有时需要在 Numpy 数组中进行填充,然后使用numPy.pad()函数。该函数返回秩等于给定数组的填充数组,形状将根据 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.
示例 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)
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)
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)
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)
输出:
[6 6 6 1 3 2 5 4 4 4]
示例 2:
蟒蛇3
# 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)
输出:
[-4 -2 -1 1 3 2 5 4 4 5]
示例 3:
蟒蛇3
# 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)
输出:
[9 9 9 1 3 9 5 4 9 9 9]
示例 4:
蟒蛇3
# 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)
输出:
[[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]]