7

When I use column_stack to concatenate NumPy arrays, the dtype gets converted:

a = numpy.array([1., 2., 3.], dtype=numpy.float64)
b = numpy.array([1, 2, 3], dtype=numpy.int64)
print numpy.column_stack((a, b)).dtype
>>> float64

Is there a way to preserve the dtype of the individual columns?

fetteelke
  • 138
  • 1
  • 6

2 Answers2

3

You can stack two arrays with numpy.lib.recfunctions method and preserve the type with it:

>>> from  numpy.lib.recfunctions import append_fields

>>> a = numpy.rec.array(a, dtype=[('a', numpy.float64)])
>>> new_a = append_fields(a, 'b', b, usemask=False, dtypes=[numpy.int64])
>>> new_a
array([(1.0, 1), (2.0, 2), (3.0, 3)], 
      dtype=[('a', '<f8'), ('b', '<i8')])

>>> new_a['a']
array([ 1.,  2.,  3.])

>>> new_a['b']
array([1, 2, 3])
Dalek
  • 4,168
  • 11
  • 48
  • 100
1

My arrays got converted into string (S18) when I column_stack'ed em.

I used astype(desired dtype) to convert them back to what they were after the stacking.

http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.astype.html

example:

new_array= old_array.astype(float64) 
Labibah
  • 5,371
  • 6
  • 25
  • 23