“扩展"网站的好方法一个numpy的ndarray? [英] Good ways to "expand" a numpy ndarray?

查看:106
本文介绍了“扩展"网站的好方法一个numpy的ndarray?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有好的方法来扩展"一个numpy ndarray?说我有一个像这样的ndarray:

Are there good ways to "expand" a numpy ndarray? Say I have an ndarray like this:

[[1 2]
 [3 4]]

我希望每一行通过填充零来包含更多元素:

And I want each row to contains more elements by filling zeros:

[[1 2 0 0 0]
 [3 4 0 0 0]]

我知道必须有一些蛮力的方法(比如用零构造一个更大的数组,然后从旧的较小的数组中复制元素),只是想知道是否有Python的方法来做到这一点.尝试了numpy.reshape但没有用:

I know there must be some brute-force ways to do so (say construct a bigger array with zeros then copy elements from old smaller arrays), just wondering are there pythonic ways to do so. Tried numpy.reshape but didn't work:

import numpy as np
a = np.array([[1, 2], [3, 4]])
np.reshape(a, (2, 5))

Numpy抱怨:ValueError: total size of new array must be unchanged

推荐答案

有索引技巧r_c_.

>>> import numpy as np
>>> a = np.array([[1, 2], [3, 4]])
>>> z = np.zeros((2, 3), dtype=a.dtype)
>>> np.c_[a, z]
array([[1, 2, 0, 0, 0],
       [3, 4, 0, 0, 0]])

如果这是对性能至关重要的代码,则您可能更喜欢使用等效的np.concatenate而不是索引技巧.

If this is performance critical code, you might prefer to use the equivalent np.concatenate rather than the index tricks.

>>> np.concatenate((a,z), axis=1)
array([[1, 2, 0, 0, 0],
       [3, 4, 0, 0, 0]])

还有np.resizenp.ndarray.resize,但是它们有一些限制(由于numpy在内存中布置数据的方式),因此请读取这些字符串上的文档字符串.您可能会发现,简单地串联会更好.

There are also np.resize and np.ndarray.resize, but they have some limitations (due to the way numpy lays out data in memory) so read the docstring on those ones. You will probably find that simply concatenating is better.

顺便说一句,当我需要执行此操作时,我通常只是按照您已经提到的基本方法进行操作(创建一个零数组并在其中分配较小的数组),我看不到任何错误接着就,随即!

By the way, when I've needed to do this I usually just do it the basic way you've already mentioned (create an array of zeros and assign the smaller array inside it), I don't see anything wrong with that!

这篇关于“扩展"网站的好方法一个numpy的ndarray?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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