gpt4 book ai didi

python - 为什么 pandas 会将大于 2**63-1 的 unsigned int 转换为对象?

转载 作者:太空狗 更新时间:2023-10-30 00:02:13 24 4
gpt4 key购买 nike

当我将 numpy 数组转换为 pandas 数据帧时,如果整数大于 2^63 - 1,pandas 会将 uint64 类型更改为对象类型。

import pandas as pd
import numpy as np

x = np.array([('foo', 2 ** 63)], dtype = np.dtype([('string', np.str_, 3), ('unsigned', np.uint64)]))
y = np.array([('foo', 2 ** 63 - 1)], dtype = np.dtype([('string', np.str_, 3), ('unsigned', np.uint64)]))

print pd.DataFrame(x).dtypes.unsigned
dtype('O')
print pd.DataFrame(y).dtypes.unsigned
dtype('uint64')

这很烦人,因为我无法将数据框写入表格格式的 hdf 文件:

pd.DataFrame(x).to_hdf('x.hdf', 'key', format = 'table')

输出:

TypeError: 无法序列化列 [unsigned] 因为它的数据内容是 [integer] object dtype

谁能解释一下类型转换?

最佳答案

这是一个 open bug , 但你可以强制它回到 uint64 using DataFrame.astype()

x = np.array([('foo', 2 ** 63)], dtype = np.dtype([('string', np.str_, 3), ('unsigned', np.uint64)]))

a = pd.DataFrame(x)
a['unsigned'] = a['unsigned'].astype(np.uint64)
>>>a.dtypes
string object
unsigned uint64
dtype: object

用于将数据类型转换为数值的其他方法引发错误或不起作用:

>>>pd.to_numeric(a['unsigned'], errors = coerce)
OverflowError: Python int too large to convert to C long

>>>a.convert_objects(convert_numeric = True).dtypes
string object
unsigned object
dtype: object

关于python - 为什么 pandas 会将大于 2**63-1 的 unsigned int 转换为对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34283319/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com