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

查看:113
本文介绍了如何将项目添加到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那样轻松或有效地做到这一点.您会发现,每个追加"操作都需要重新分配阵列内存,并且短期内需要增加一倍的内存.因此,解决该问题的更一般的方法是尝试将数组分配为与算法的最终输出一样大.然后对子集执行所有操作(切片).理想情况下,应尽量减少阵列的创建和破坏.

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:

对于二维数组:

  • np.hstack
  • np.vstack
  • np.column_stack
  • np.row_stack

对于3D数组(上面有加号):

for 3-D arrays (the above plus):

对于N-D阵列:

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

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