📜  Python中的 numpy.pad()函数

📅  最后修改于: 2022-05-13 01:54:27.827000             🧑  作者: Mango

Python中的 numpy.pad()函数

numpy.pad()函数用于填充 Numpy 数组。有时需要在 Numpy 数组中进行填充,然后使用numPy.pad()函数。该函数返回秩等于给定数组的填充数组,形状将根据 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]]