简体   繁体   English

将一维 numpy ndarray 分配到二维数组的列中

[英]Assign 1d numpy ndarray into columns of a 2d array

Assume dst is an ndarray with shape (5, N), and ramp is an ndarray with shape (5,).假设dst是一个形状为 (5, N) 的 ndarray,而ramp是一个形状为 (5,) 的 ndarray。 (In this case, N = 2): (在这种情况下,N = 2):

>>> dst = np.zeros((5, 2))
>>> dst
array([[0., 0.],
       [0., 0.],
       [0., 0.],
       [0., 0.],
       [0., 0.]])
>>> ramp = np.linspace(1.0, 2.0, 5)
>>> ramp
array([1.  , 1.25, 1.5 , 1.75, 2.  ])

Now I'd like to copy ramp into the columns of dst, resulting in this:现在我想将ramp复制到dst的列中,结果是:

>>> dst
array([[1., 1.],
       [1.25., 1.25.],
       [1.5., 1.5.],
       [1.75, 1.75],
       [2.0, 2.0]])

I didn't expect this to work, and it doesn't:我没想到这会起作用,而且它没有:

>>> dst[:] = ramp
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not broadcast input array from shape (5) into shape (5,2)

This works, but I'm certain there's a more "numpyesque" way to accomplish this:这有效,但我确定有一种更“numpyesque”的方式来实现这一点:

>>> dst[:] = ramp.repeat(dst.shape[1]).reshape(dst.shape)
>>> dst
array([[1.  , 1.  ],
       [1.25, 1.25],
       [1.5 , 1.5 ],
       [1.75, 1.75],
       [2.  , 2.  ]]) 

Any ideas?有任何想法吗?

note笔记

Unlike "Cloning" row or column vectors , I want to assign ramp into dst (or even a subset of dst ).“克隆”行或列向量不同,我想将ramp分配到dst (甚至是dst的子集)。 In addition, the solution given there uses a python array as the source, not an ndarray, and thus requires calls to .transpose, etc.此外,那里给出的解决方案使用 python 数组作为源,而不是 ndarray,因此需要调用 .transpose 等。

Method 1 : Use broadcasting:方法一:使用广播:

As OP mentioned in the comment.正如评论中提到的OP。 Broadcasting works on assigment too广播也适用于分配

dst[:] = ramp[:,None]

Method 2 : Use column_stack方法 2 :使用column_stack

N = dst.shape[1]
dst[:] = np.column_stack([ramp.tolist()]*N)

Out[479]:
array([[1.  , 1.  ],
       [1.25, 1.25],
       [1.5 , 1.5 ],
       [1.75, 1.75],
       [2.  , 2.  ]])

Method 3 : use np.tile方法三:使用np.tile

N = dst.shape[1]
dst[:] = np.tile(ramp[:,None], (1,N))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM