[英]How can I make a padded numpy array using the first/last row/column as the pad?
I am in need of efficiently padding a numpy array on all 4 sides, using the first and last row/column as the padding data. 我需要使用第一行和最后一行/列作为填充数据,在所有4个面上高效填充numpy数组。 For example, given the following: 例如,给出以下内容:
A=np.array([[1 2 3 4],
[5 6 7 8],
[9 10 11 12]])
I am trying to end up with: 我试图以:
B=np.array([[1 1 2 3 4 4],
[1 1 2 3 4 4],
[5 5 6 7 8 8],
[9 9 10 11 12 12],
[9 9 10 11 12 12]])
Notice the original array A is located at: B[1:-1,1:-1]. 请注意,原始数组A位于:B [1:-1,1:-1]。 I assume I could pad in one direction first (horizontal or vertical) than the other, to get the duplicated corner values. 我假设我可以先在一个方向(水平或垂直)上进行填充,以获取重复的角值。 However, my vectorization/numpification is failing me. 但是,我的矢量化/数字化使我失望。 (Note: the array I am doing this with is quite large, and i need to perform this option many times, so doing it efficiently is key- I can do it with a loop, but it is quite slow). (注意:我正在使用的数组很大,我需要多次执行此选项,因此有效地执行此操作很关键-我可以使用循环来执行此操作,但是速度很慢)。
With np.pad
, you can specify the width of padding and the padding mode to apply to an array. 使用np.pad
,您可以指定填充的宽度和应用于数组的填充模式。 For your example array, the edge
padding mode gives the desired result: 对于示例数组, edge
填充模式可提供所需的结果:
>>> np.pad(A, 1, 'edge')
array([[ 1, 1, 2, 3, 4, 4],
[ 1, 1, 2, 3, 4, 4],
[ 5, 5, 6, 7, 8, 8],
[ 9, 9, 10, 11, 12, 12],
[ 9, 9, 10, 11, 12, 12]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.