python - numpy:使用 column_stack 时是否可以保留列的 dtype

标签 python numpy

当我使用 column_stack 连接 NumPy 数组时,dtype 被转换:

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

最佳答案

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

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

关于python - numpy:使用 column_stack 时是否可以保留列的 dtype,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26018781/

相关文章:

javascript - web2py:如何将 python 数组复制到 javascript 数组中

python - 通过从 PyQt4 中使用 QSplitter() 设置的按钮调用来删除小部件

python - 更新列表中的匹配行

python - 去除标点符号,输出剩余文本-Python 3 Function

python - 当 '?' 不起作用时,如何在 sqlite3 语句中为列名和表名使用占位符?

python - 如何调整行或列中的具体数据?

python - 根据关键字和位置数据识别文档中的 block /词组?

python - 附加具有不同维度的 numpy 数组

python - 从 32 位移动到 64 位后 PyQtGraph 不工作

python - 使用 slider 编辑颜色值