Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append Row(s) to a NumPy Record Array

Tags:

python

numpy

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

like image 420
ebressert Avatar asked Nov 13 '09 15:11

ebressert


People also ask

How can I add one row in NumPy?

append() Sometimes we have an empty array and we need to append rows in it. Numpy provides the function to append a row to an empty Numpy array using numpy. append() function.

How do you add a row to an array in Python?

Import numpy library and create a numpy array. Pass the array, row to be added to the append() method and set axis=0. The append() method will return copy of the array by adding the row. Print the new array.

Does append work on NumPy array?

NumPy append() SyntaxThe arr can be an array-like object or a NumPy array. The values are appended to a copy of this array. The values are array-like objects and it's appended to the end of the “arr” elements. The axis specifies the axis along which values are appended.


1 Answers

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)]

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).

like image 175
unutbu Avatar answered Oct 16 '22 17:10

unutbu