4

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?

3
  • Define a composite dtype, make a np.zeros(...) from it, and assign the respective fields. Your link has more information on creating structured arrays. I don't think it mentions column_stack. Commented Feb 17, 2020 at 20:52
  • If using Pandas isn't an issue then could simply do pd.DataFrame({'a':a, 'b':b}) - should preserve dtypes Commented Feb 17, 2020 at 20:57
  • 1
    np.rec.fromarrays([a,b]) if a recarray is ok Commented Feb 18, 2020 at 2:41

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.