繁体   English   中英

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

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

假设dst是一个形状为 (5, N) 的 ndarray,而ramp是一个形状为 (5,) 的 ndarray。 (在这种情况下,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.  ])

现在我想将ramp复制到dst的列中,结果是:

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

我没想到这会起作用,而且它没有:

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

这有效,但我确定有一种更“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.  ]]) 

有任何想法吗?

笔记

“克隆”行或列向量不同,我想将ramp分配到dst (甚至是dst的子集)。 此外,那里给出的解决方案使用 python 数组作为源,而不是 ndarray,因此需要调用 .transpose 等。

方法一:使用广播:

正如评论中提到的OP。 广播也适用于分配

dst[:] = ramp[:,None]

方法 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.  ]])

方法三:使用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