【问题标题】:Numpy resize and fill with specific valueNumpy 调整大小并填充特定值
【发布时间】:2016-09-29 06:33:51
【问题描述】:

如何调整 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)

如果我使用 resize 我无法指定我想要使用的值。

>>> 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

【问题讨论】:

标签: python numpy resize


【解决方案1】:

您的数组有一个固定大小的数据缓冲区。您可以在不更改该缓冲区的情况下重塑数组。您可以在不更改缓冲区的情况下获取切片 (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]])

【讨论】:

    【解决方案2】:

    为了缩短它,你可以在 slice 中使用负值:

    >>> 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)
    

    【讨论】:

    • 是的,但我想调整数组的大小,所以有时我需要减少一个维度并增加另一个维度,我想知道最好的方法(并使用 less if 语句)跨度>
    猜你喜欢
    • 1970-01-01
    • 2019-07-04
    • 2012-08-14
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2010-10-19
    • 2022-01-09
    • 2011-01-03
    相关资源
    最近更新 更多