如何将项目添加到 numpy 数组中 [英] How to add items into a numpy array

查看:32
本文介绍了如何将项目添加到 numpy 数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要完成以下任务:

来自:

a = array([[1,3,4],[1,2,3]...[1,2,1]])

(每行添加一个元素)到:

(add one element to each row) to:

a = array([[1,3,4,x],[1,2,3,x]...[1,2,1,x]])

我尝试过像 a[n] = array([1,3,4,x]) 之类的东西

I have tried doing stuff like a[n] = array([1,3,4,x])

但 numpy 抱怨形状不匹配.我尝试遍历 a 并将元素 x 附加到每个项目,但未反映更改.

but numpy complained of shape mismatch. I tried iterating through a and appending element x to each item, but the changes are not reflected.

关于如何实现这一点有什么想法吗?

Any ideas on how I can accomplish this?

推荐答案

将数据附加到现有数组对于任何有 Python 经验的人来说都是一件很自然的事情.但是,如果您发现自己经常附加到大型数组,您会很快发现 NumPy 不像 python list 那样轻松或有效地执行此操作.您会发现每个追加"操作都需要重新分配阵列内存和短期内存需求翻倍.因此,该问题的更通用解决方案是尝试将数组分配为与算法的最终输出一样大.然后对子集执行所有操作(slices) 的那个数组.理想情况下应尽量减少数组的创建和销毁.

Appending data to an existing array is a natural thing to want to do for anyone with python experience. However, if you find yourself regularly appending to large arrays, you'll quickly discover that NumPy doesn't easily or efficiently do this the way a python list will. You'll find that every "append" action requires re-allocation of the array memory and short-term doubling of memory requirements. So, the more general solution to the problem is to try to allocate arrays to be as large as the final output of your algorithm. Then perform all your operations on sub-sets (slices) of that array. Array creation and destruction should ideally be minimized.

也就是说,这通常是不可避免的,执行此操作的函数是:

That said, It's often unavoidable and the functions that do this are:

对于二维数组:

对于 3-D 数组(上述加分项):

for 3-D arrays (the above plus):

对于 N 维数组:

这篇关于如何将项目添加到 numpy 数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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