调整大小和拉伸NumPy数组 [英] Resizing and stretching a NumPy array

查看:75
本文介绍了调整大小和拉伸NumPy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python工作,并且有一个 NumPy 数组,如下所示:

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.

推荐答案

@KennyTM的答案非常巧妙,确实适合您的情况,但作为替代方案,它可能会为扩展数组提供更多的灵活性,请尝试np.repeat:

@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:

>>> a = np.array([[1, 5, 9],
              [2, 7, 3],
              [8, 4, 6]])

>>> np.repeat(a,2, axis=1)
array([[1, 1, 5, 5, 9, 9],
       [2, 2, 7, 7, 3, 3],
       [8, 8, 4, 4, 6, 6]])

因此,这完成了沿一个轴的重复,以使其沿多个轴(如您所愿),只需嵌套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:

>>> np.repeat(np.repeat(a,2, axis=0), 2, axis=1)
array([[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]])

您还可以更改任何初始行或列的重复次数.例如,如果您希望除最后一行外每行重复两次:

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:

>>> np.repeat(a, [2,2,1], axis=0)
array([[1, 5, 9],
       [1, 5, 9],
       [2, 7, 3],
       [2, 7, 3],
       [8, 4, 6]])

这里,当第二个参数为list时,它指定逐行(在这种情况下,由于axis=0而行)对每一行重复.

Here when the second argument is a list it specifies a row-wise (rows in this case because axis=0) repeats for each row.

这篇关于调整大小和拉伸NumPy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆