简体   繁体   English

如何使用第一行/最后一行/列作为填充来创建填充的numpy数组?

[英]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.

相关问题 使用 numpy 操作从每行填充 numpy 数组(不包括填充)和未填充值的数量中获取 Select 的最快方法 - Fastest way to Select a random number from each row padded numpy array (excluding the pad) and number of non padded values, using numpy operations 切片二维 NumPy 数组,删除第一行和最后一行和列 - Slicing 2D NumPy Array, removing first and last row and column 如何用图像的中值有效填充 RGB numpy 数组? - How can I efficently pad an RGB numpy array with the median of the image? 如何按列而不是按行将我的 dataframe 变成 numpy 数组? - How can I make my dataframe into a numpy array by column rather than by row? 如何使用numpy将矢量填充和/或截断到指定的长度? - How can I pad and/or truncate a vector to a specified length using numpy? 如何在每行中获取 n 个最后/第一个 True 的 NumPy 数组 - How to get NumPy array of n last/first Trues in each row 如何将 1D numpy 数组添加到 2D numpy 数组的第一列? - How can I add 1D numpy array to the first column of a 2D numpy array? 如何移动numpy数组的列,以使前两个列转到最后一个而最后两个列到第一个? - How can I shift columns of numpy array so that the first two colums go to the last and the last two come to the first? 将新的第一列和最后一列添加到 numpy 数组 - adding new first and last column to a numpy array 如何在不使用循环的情况下将 numpy 矩阵中的每一行除以同一行的最后一个元素? - How can I divide each row in a numpy matrix by the last element of that same row, without using loops?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM