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

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

问题描述

是否有扩展"numpy ndarray 的好方法?假设我有一个这样的 ndarray:

[[1 2][3 4]]

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

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

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

将 numpy 导入为 npa = np.array([[1, 2], [3, 4]])np.reshape(a, (2, 5))

Numpy 抱怨:ValueError:新数组的总大小必须保持不变

解决方案

有索引技巧r_c_.

<预><代码>>>>将 numpy 导入为 np>>>a = np.array([[1, 2], [3, 4]])>>>z = np.zeros((2, 3), dtype=a.dtype)>>>np.c_[a, z]数组([[1, 2, 0, 0, 0],[3, 4, 0, 0, 0]])

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

<预><代码>>>>np.concatenate((a,z),axis=1)数组([[1, 2, 0, 0, 0],[3, 4, 0, 0, 0]])

还有 np.resizenp.ndarray.resize,但它们有一些限制(由于 numpy 在内存中布置数据的方式)所以阅读那些的文档字符串.您可能会发现简单地连接更好.

顺便说一句,当我需要这样做时,我通常只是按照您已经提到的基本方法进行操作(创建一个零数组并在其中分配较小的数组),我看不出有什么问题接着就,随即!

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

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 complains that: ValueError: total size of new array must be unchanged

解决方案

There are the index tricks r_ and 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]])

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

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