Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding row to numpy recarray

Tags:

python

numpy

Is there an easy way to add a record/row to a numpy recarray without creating a new recarray? 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.

like image 815
astrofrog Avatar asked Oct 21 '09 01:10

astrofrog


People also ask

How do I add a row to a NumPy matrix?

Use the numpy. append() Function to Add a Row to a Matrix in NumPy. The append() function from the numpy module can add elements to the end of the array. By specifying the axis as 0, we can use this function to add rows to a matrix.

How do I assign a row in NumPy?

Rows and columns of NumPy arrays can be selected or modified using the square-bracket indexing notation in Python. To select a row in a 2D array, use P[i] . For example, P[0] will return the first row of P . To select a column, use P[:, i] .

How do I add a row to an existing array in Python?

You can use numpy. append() to append a row to numpty array and reshape to a matrix later on.


1 Answers

You can call yourrecarray.resize with a shape which has one more row, then assign to that new row. 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!-)

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)]
like image 118
Alex Martelli Avatar answered Oct 06 '22 00:10

Alex Martelli