Numpy调整大小并填充特定值

时间:2016-05-31 09:53:31

标签: python numpy resize

如何调整numpy数组的大小并用特定值填充(如果扩展某个维度)?

我找到了一种用 np.pad 来扩展数组的方法,但我不能缩短它:

>>> import numpy as np
>>> a = np.ndarray((5, 5), dtype=np.uint16)
>>> a
array([[0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]], dtype=uint16)
>>> np.pad(a, ((0, 1), (0,3)), mode='constant', constant_values=9)
array([[0, 0, 0, 0, 0, 9, 9, 9],
       [0, 0, 0, 0, 0, 9, 9, 9],
       [0, 0, 0, 0, 0, 9, 9, 9],
       [0, 0, 0, 0, 0, 9, 9, 9],
       [0, 0, 0, 0, 0, 9, 9, 9],
       [9, 9, 9, 9, 9, 9, 9, 9]], dtype=uint16)

如果我使用调整大小,我无法指定我想要使用的值。

>>> a.fill(5)
>>> a.resize((2, 7))
>>> a
array([[5, 5, 5, 5, 5, 5, 5],
       [5, 5, 5, 5, 5, 5, 5]], dtype=uint16)

但我想

>>> a
array([[5, 5, 5, 5, 5, 9, 9],
       [5, 5, 5, 5, 5, 9, 9]], dtype=uint16)

经过一些测试我创建了这个函数,但它只在你更改x_value或y_value较低时才有效,如果你需要增加y维度它不起作用,为什么?

VALUE_TO_FILL = 9
def resize(self, x_value, y_value):
    x_diff = self.np_array.shape[0] - x_value
    y_diff = self.np_array.shape[1] - y_value
    self.np_array.resize((x_value, y_value), refcheck=False)
    if x_diff < 0:
        self.np_array[x_diff:, :] = VALUE_TO_FILL
    if y_diff < 0:
        self.np_array[:, y_diff:] = VALUE_TO_FILL

2 个答案:

答案 0 :(得分:2)

您的数组具有固定大小的数据缓冲区。您可以在不更改缓冲区的情况下重塑阵列。您可以在不更改缓冲区的情况下获取切片(view)。但是,如果不更改缓冲区,则无法向数组添加值。

通常resize返回一个带有新数据缓冲区的新数组。

pad是处理一般情况的复杂函数。但最简单的方法是创建empty目标数组,填充它,然后将输入复制到正确的位置。

或者pad可以创建填充数组并将它们与原始数组连接起来。但concatenate也会返回空白并复制。

使用剪辑自己做的垫可以结构化为:

n,m = X.shape
R = np.empty((k,l))
R.fill(value)
<calc slices from n,m,k,l>
R[slice1] = X[slice2]

计算切片可能需要if-else次测试或等效min/max。你可以搞清楚这些细节。

这可能是所有需要的

R[:X.shape[0],:X.shape[1]]=X[:R.shape[0],:R.shape[1]]

那是因为如果切片大于尺寸,则没有问题。

In [37]: np.arange(5)[:10]
Out[37]: array([0, 1, 2, 3, 4])

因此,例如:

In [38]: X=np.ones((3,4),int)    
In [39]: R=np.empty((2,5),int)
In [40]: R.fill(9)

In [41]: R[:X.shape[0],:X.shape[1]]=X[:R.shape[0],:R.shape[1]]

In [42]: R
Out[42]: 
array([[1, 1, 1, 1, 9],
       [1, 1, 1, 1, 9]])

答案 1 :(得分:0)

要缩短它,可以在切片中使用负值:

>>> import numpy as np
>>> a = np.ndarray((5, 5), dtype=np.uint16)
>>> a
array([[0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]], dtype=uint16)
>>> b = a[0:-1,0:-3]
>>> b
array([[0, 0],
       [0, 0],
       [0, 0],
       [0, 0]], dtype=uint16)
相关问题