将行追加到NumPy记录数组 [英] Append Row(s) to a NumPy Record Array

查看:107
本文介绍了将行追加到NumPy记录数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将行附加到NumPy rec.array()?例如

Is there a way to append a row to a NumPy rec.array()? For example,

x1=np.array([1,2,3,4])
x2=np.array(['a','dd','xyz','12'])
x3=np.array([1.1,2,3,4])
r = np.core.records.fromarrays([x1,x2,x3],names='a,b,c')

append(r,(5,'cc',43.0),axis=0)

最简单的方法是将所有列提取为nd.array()类型,将单独的元素添加到每一列,然后重新构建rec.array().不幸的是,此方法将导致内存效率低下.还有另一种方法可以不分离重建rec.array()吗?

The easiest way would to extract all the column as nd.array() types, add the separate elements to each column, and then rebuild the rec.array(). This method would be memory inefficient unfortunately. Is there another way to this without separating the rebuilding the rec.array()?

干杯

Eli

推荐答案

您可以就地调整numpy数组的大小.这比转换为列表然后再转换为numpy数组的速度更快,而且使用的内存也更少.

You can resize numpy arrays in-place. This is faster than converting to lists and then back to numpy arrays, and it uses less memory too.

print (r.shape)
# (4,)
r.resize(5)   
print (r.shape)
# (5,)
r[-1] = (5,'cc',43.0)
print(r)

# [(1, 'a', 1.1000000000000001) 
#  (2, 'dd', 2.0) 
#  (3, 'xyz', 3.0) 
#  (4, '12', 4.0)
#  (5, 'cc', 43.0)]

如果没有足够的内存来就地扩展数组,则调整大小(或附加)操作可能会强制NumPy为全新数组分配空间,并将旧数据复制到新位置.那自然很慢,因此,如果可能的话,您应尽量避免使用resizeappend.相反,应从一开始就预先分配足够大小的数组(即使比最终所需的数组大一些).

If there is not enough memory to expand an array in-place, the resizing (or appending) operation may force NumPy to allocate space for an entirely new array and copy the old data to the new location. That, naturally, is rather slow so you should try to avoid using resize or append if possible. Instead, pre-allocate arrays of sufficient size from the very beginning (even if somewhat larger than ultimately necessary).

这篇关于将行追加到NumPy记录数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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