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

查看:22
本文介绍了调整和拉伸 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]

这些只是一些示例数组,我实际上会调整数组的几种大小,而不仅仅是这些.

我是这方面的新手,我似乎无法理解我需要做的事情.

解决方案

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

<预><代码>>>>a = np.array([[1, 5, 9],[2, 7, 3],[8, 4, 6]])>>>np.repeat(a,2,axis=1)数组([[1, 1, 5, 5, 9, 9],[2, 2, 7, 7, 3, 3],[8, 8, 4, 4, 6, 6]])

因此,这完成了沿一个轴的重复,要沿多个轴进行重复(如您所愿),只需嵌套 np.repeat 调用:

<预><代码>>>>np.repeat(np.repeat(a,2,axis=0), 2,axis=1)数组([[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]])

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

<预><代码>>>>np.repeat(a, [2,2,1],axis=0)数组([[1, 5, 9],[1, 5, 9],[2, 7, 3],[2, 7, 3],[8, 4, 6]])

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

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

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

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天全站免登陆