[Numpy-discussion] how can we concatenate structured arrays ?

josef.pktd@gmai... josef.pktd@gmai...
Wed Sep 16 03:25:26 CDT 2009


I have two structured arrays of different types. How can I
horizontally concatenate the two arrays? Is there a direct way, or do
I need to start from scratch?

nobs = 10
testdata = np.random.randint(3,
size=(nobs,4)).view([('a',int),('b',int),('c',int),('d',int)])
testdatacont = np.random.normal( size=(nobs,2)).view([('e',float), ('f',float)])

>>> np.hstack((testdata,testdatacont))
Traceback (most recent call last):
  File "C:\Programs\Python25\Lib\site-packages\numpy\lib\shape_base.py",
line 505, in hstack
    return _nx.concatenate(map(atleast_1d,tup),1)
TypeError: expected a readable buffer object

>>> np.column_stack((testdata,testdatacont))
Traceback (most recent call last):
  File "C:\Programs\Python25\Lib\site-packages\numpy\lib\shape_base.py",
line 552, in column_stack
    return _nx.concatenate(arrays,1)
TypeError: expected a readable buffer object


the following works, but looks like a big detour for a simple column_stack:

>>> import numpy.lib.recfunctions
>>> dt2 = numpy.lib.recfunctions.zip_descr((testdata,testdatacont),flatten=True)
>>> joinedarr = np.array([tuple(i+j) for i,j in zip(testdata.base.tolist(), testdatacont.base.tolist())], dtype = dt2)
>>> joinedarr.dtype
dtype([('a', '<i4'), ('b', '<i4'), ('c', '<i4'), ('d', '<i4'), ('e',
'<f8'), ('f', '<f8')])


if I want to convert the dtypes to float (which I don't want in this
case), then its easier

>>> np.column_stack((testdata.base,testdatacont.base)).dtype
dtype('float64')


Josef


More information about the NumPy-Discussion mailing list