调整 NumPy 数组的大小和拉伸
我正在使用 Python 工作,并且有一个像这样的 NumPy 数组:
[1,5,9]
[2,7,3]
[8,4,6]
如何将其拉伸到某个值像下面这样?
[1,1,5,5,9,9]
[1,1,5,5,9,9]
[2,2,7,7,3,3]
[2,2,7,7,3,3]
[8,8,4,4,6,6]
[8,8,4,4,6,6]
这些只是一些示例数组,我实际上会调整数组的几个大小,而不仅仅是这些。
我对此很陌生,我似乎无法集中精力思考我需要做什么。
I am working in Python and I have a NumPy array like this:
[1,5,9]
[2,7,3]
[8,4,6]
How do I stretch it to something like the following?
[1,1,5,5,9,9]
[1,1,5,5,9,9]
[2,2,7,7,3,3]
[2,2,7,7,3,3]
[8,8,4,4,6,6]
[8,8,4,4,6,6]
These are just some example arrays, I will actually be resizing several sizes of arrays, not just these.
I'm new at this, and I just can't seem to wrap my head around what I need to do.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
@KennyTM 的答案非常巧妙,并且确实适合您的情况,但作为替代方案,可能会为扩展数组提供更大的灵活性,请尝试
np.repeat
:因此,这完成了沿一个轴的重复,要使其沿多个轴(如您可能想要的)重复,只需嵌套
np.repeat
调用:您还可以改变任何初始行或列的重复次数。例如,如果您希望除最后一行之外的每一行重复两次:
这里,当第二个参数是列表时,它指定按行(在本例中为行,因为 axis=0 ) 对每一行重复。
@KennyTM's answer is very slick, and really works for your case but as an alternative that might offer a bit more flexibility for expanding arrays try
np.repeat
:So, this accomplishes repeating along one axis, to get it along multiple axes (as you might want), simply nest the
np.repeat
calls:You can also vary the number of repeats for any initial row or column. For example, if you wanted two repeats of each row aside from the last row:
Here when the second argument is a
list
it specifies a row-wise (rows in this case becauseaxis=0
) repeats for each row.不幸的是 numpy 不允许分数步(据我所知)。这是一个解决方法。它不像 Kenny 的解决方案那么聪明,但它利用了传统的索引:
(dtlussier 的解决方案更好)
Unfortunately numpy does not allow fractional steps (as far as I am aware). Here is a workaround. It's not as clever as Kenny's solution, but it makes use of traditional indexing:
(dtlussier's solution is better)