简体   繁体   English

将行添加到numpy重新排列

[英]Adding row to numpy recarray

Is there an easy way to add a record/row to a numpy recarray without creating a new recarray? 是否有一种简单的方法可以将记录/行添加到numpy重新排列而无需创建新的重新排列? Let's say I have a recarray that takes 1Gb in memory, I want to be able to add a row to it without having python take up 2Gb of memory temporarily. 假设我有一个在内存中占用1Gb的重新排列,我希望能够在没有python暂时占用2Gb内存的情况下添加一行。

You can call yourrecarray.resize with a shape which has one more row, then assign to that new row. 您可以使用另外一行的形状调用yourrecarray.resize ,然后分配给该新行。 Of course. 当然。 numpy might still have to allocate completely new memory if it just doesn't have room to grow the array in-place, but at least you stand a chance!-) numpy 可能仍然必须分配全新的内存,如果它没有空间来就地增长阵列,但至少你有机会! - )

Since an example was requested, here comes, modified off the canonical example list ...: 由于请求了一个示例,这里是修改了规范示例列表 ...:

>>> import numpy
>>> mydescriptor = {'names': ('gender','age','weight'), 'formats': ('S1', 'f4', 'f4')} 
>>> a = numpy.array([('M',64.0,75.0),('F',25.0,60.0)], dtype=mydescriptor)
>>> print a
[('M', 64.0, 75.0) ('F', 25.0, 60.0)]
>>> a.shape
(2,)
>>> a.resize(3)
>>> a.shape
(3,)
>>> print a
[('M', 64.0, 75.0) ('F', 25.0, 60.0) ('', 0.0, 0.0)]
>>> a[2] = ('X', 17.0, 61.5)
>>> print a
[('M', 64.0, 75.0) ('F', 25.0, 60.0) ('X', 17.0, 61.5)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM