numpy:使用column_stack时是否可以保留列的dtype [英] numpy: is it possible to preserve the dtype of columns when using column_stack

查看:84
本文介绍了numpy:使用column_stack时是否可以保留列的dtype的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用column_stack串联NumPy数组时,dtype得到转换:

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

是否可以保留各个列的dtype?

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

推荐答案

您可以使用numpy.lib.recfunctions方法堆叠两个数组并使用它保存类型:

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])

这篇关于numpy:使用column_stack时是否可以保留列的dtype的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆