Numpy resize array with repeated values

时间:2018-02-01 18:16:46

标签: python arrays numpy

Suppose a vector whose items can take values from a finite set ([7, 8, 9] for example). I try to search the vector that meets some requirements. I use numpy array to store possible states of a vector items. At first my vector is in indeterminate state that looks like that

>>> A = np.tile([7, 8, 9], (3, 1))
>>> A
array([[7, 8, 9],
       [7, 8, 9],
       [7, 8, 9]])

My algorithm works (the details of algo are irrelevant here) by reducing the possible states for each cell. For example, if I want to claim that the first item can be only 9, it works well, thanks to the second broadcasting rule:

>>> A[0] = 9
>>> A
array([[9, 9, 9],
       [7, 8, 9],
       [7, 8, 9]])

However, if I want to claim that the item cannot be 8, and try to assign [7, 9] to it:

>>> A[1] = [7, 9]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: cannot copy sequence with size 2 to array axis with dimension 3

What I want to achieve here is some kind of resizing that will automatically pad the value to desired length, e.g [7, 9, 9] or [7, 9, 7]. I do not care about the exact value, the only thing that matters is that set(A[1]) == {7, 9} after that operation.

Is it possible to do such a resize automatically with numpy?

1 个答案:

答案 0 :(得分:1)

有一些低级操作可以根据需要重复数组项。它们并不常用。我会想到np.putnp.place,但它们在扁平数组上工作,并且需要布尔屏蔽。但resize可能会在这里完成工作:

In [17]: np.resize([7,9],3)
Out[17]: array([7, 9, 7])
In [18]: A[1,:] = np.resize([7,9], A.shape[1])
In [19]: A
Out[19]: 
array([[7, 8, 9],
       [7, 9, 7],
       [7, 8, 9]])

它甚至适用于更大的数组:

In [20]: A[1,:] = np.resize([1,2,3,4], A.shape[1])
In [21]: A
Out[21]: 
array([[7, 8, 9],
       [1, 2, 3],
       [7, 8, 9]])

我还没有使用resize,也不知道它的局限性或怪癖。

将此行为视为“广播”令人困惑。它扩展了一些非常具体的规则,这些规则适用于程序和用户,因为它们是明确的。