Numpy:如何将一个数组堆放到较大数组的每一行中并将其变成2D数组?
我有一个名为Heartbeats
的Numpy数组,有100行。每行都有5个元素。
我还有一个名为time_index
的单个数组,带有5个元素。 我需要将时间索引
预先到Heartbeats
的每一行。
heartbeats = np.array([
[-0.58, -0.57, -0.55, -0.39, -0.40],
[-0.31, -0.31, -0.32, -0.46, -0.46]
])
time_index = np.array([-2, -1, 0, 1, 2])
我需要的是:
array([-2, -0.58],
[-1, -0.57],
[0, -0.55],
[1, -0.39],
[2, -0.40],
[-2, -0.31],
[-1, -0.31],
[0, -0.32],
[1, -0.46],
[2, -0.46])
我只写了两行heartbeats
来说明。
I have a numpy array named heartbeats
with 100 rows. Each row has 5 elements.
I also have a single array named time_index
with 5 elements.
I need to prepend the time index
to each row of heartbeats
.
heartbeats = np.array([
[-0.58, -0.57, -0.55, -0.39, -0.40],
[-0.31, -0.31, -0.32, -0.46, -0.46]
])
time_index = np.array([-2, -1, 0, 1, 2])
What I need:
array([-2, -0.58],
[-1, -0.57],
[0, -0.55],
[1, -0.39],
[2, -0.40],
[-2, -0.31],
[-1, -0.31],
[0, -0.32],
[1, -0.46],
[2, -0.46])
I only wrote two rows of heartbeats
to illustrate.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设您使用的是numpy,则可以通过
time_index
的重复版本使用heartbeats
的ravel版本堆叠time_index
:Assuming you are using numpy, the exact output array you are looking for can be made by stacking a repeated version of
time_index
with the raveled version ofheartbeats
:另一种方法,使用广播
制造目标数组:
然后将其重塑为2D:
[17]
采用A(5,),将其扩展到(1,5),然后将其扩展到(2,5)对于插入。阅读广播
。Another approach, using broadcasting
Make a target array:
and then reshape to 2d:
[17]
takes a (5,), expands it to (1,5), and then to (2,5) for the insert. Read up onbroadcasting
.作为另一种方式,您可以根据指定的时间重复
time_index
np.concatenate :使用
np.concatenate
可能比np.tile 。该解决方案比 MAD物理学家更快,但是最快的是使用广播为 hpaulj 的答案。
As an alternative way, you can repeat
time_index
bynp.concatenate
based on the specified times:Using
np.concatenate
may be faster thannp.tile
. This solution is faster than Mad Physicist, but the fastest is using broadcasting as hpaulj's answer.