3

I have two Numpy record arrays that have exactly the same fields. What is the easiest way to combine them into one (i.e. append one table on to the other)?

astrofrog
  • 32,883
  • 32
  • 90
  • 131

3 Answers3

7

Use numpy.hstack():

>>> import numpy
>>> desc = {'names': ('gender','age','weight'), 'formats': ('S1', 'f4', 'f4')} 
>>> a = numpy.array([('M',64.0,75.0),('F',25.0,60.0)], dtype=desc)
>>> numpy.hstack((a,a))
array([('M', 64.0, 75.0), ('F', 25.0, 60.0), ('M', 64.0, 75.0),
       ('F', 25.0, 60.0)], 
      dtype=[('gender', '|S1'), ('age', '<f4'), ('weight', '<f4')])
rcs
  • 67,191
  • 22
  • 172
  • 153
0
for i in array1:
    array2.append(i)

Or (if implemented)

array1.extend(array2)

Now array1 contains also all elements of array2

OverLex
  • 2,501
  • 1
  • 24
  • 27
0
#!/usr/bin/env python
import numpy as np
desc = {'names': ('gender','age','weight'), 'formats': ('S1', 'f4', 'f4')} 
a = np.array([('M',64.0,75.0),('F',25.0,60.0)], dtype=desc)
b = np.array([('M',64.0,75.0),('F',25.0,60.0)], dtype=desc)
alen=a.shape[0]
blen=b.shape[0]
a.resize(alen+blen)
a[alen:]=b[:]

This works with structured arrays, though not recarrays. Perhaps this is a good reason to stick with structured arrays.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • Is there a reason why this does not work with recarrays? I thought recarrays were just structured arrays with an extra __getattribute__/__setattr__ arguments? – astrofrog Nov 10 '09 at 15:55
  • I don't know why. I only know that when I try the same thing with recarrays I get a ValueError: cannot resize this array: it does not own its own data. Having run into problems like this with recarrays in the past, I tend to use structured arrays instead of recarrays. The syntactic sugar isn't worth the trouble. – unutbu Nov 10 '09 at 17:03