tags:

views:

478

answers:

2

Hi Everyone,

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)

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()?

Cheers,

Eli

A: 
np.core.records.fromrecords(r.tolist()+[(5,'cc',43.)])

Still it does split, this time by rows. Maybe better?

Paul
@Paul, the question is: `"is there a more efficient way to do this"`?
mjv
+2  A: 

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)
# append(r,(5,'cc',43.0),axis=0)
r.resize(5)   
print (r.shape)
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)]
unutbu