combining two numpy arrays of different dtype to a structured array

Nico Schlömer :

I have a numpy float array and an int array of the same length. I would like to concatenate them such that the output has the composite dtype (float, int). column_stacking them together just yields a float64 array:

import numpy

a = numpy.random.rand(5)
b = numpy.random.randint(0, 100, 5)

ab = numpy.column_stack([a, b])
print(ab.dtype)
float64

Any hints?

hpaulj :

Create a 'blank' array:

In [391]: dt = np.dtype('f,i')                                                                 
In [392]: arr = np.zeros(5, dtype=dt)                                                          
In [393]: arr                                                                                  
Out[393]: 
array([(0., 0), (0., 0), (0., 0), (0., 0), (0., 0)],
      dtype=[('f0', '<f4'), ('f1', '<i4')])

fill it:

In [394]: arr['f0']=np.random.rand(5)                                                          
In [396]: arr['f1']=np.random.randint(0,100,5)                                                 
In [397]: arr                                                                                  
Out[397]: 
array([(0.40140057, 75), (0.93731374, 99), (0.6226782 , 48),
       (0.01068745, 68), (0.19197434, 53)],
      dtype=[('f0', '<f4'), ('f1', '<i4')])

There are recfunctions that can be used as well, but it's good to know (and understand) this basic approach.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=5329&siteId=1