加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 为什么pd.to_numeric不能用大数字?

发布时间:2020-12-20 11:09:04 所属栏目:Python 来源:网络整理
导读:假设我在字符串中有一个大数字,例如’555555555555555555555′.可以选择将其转换为int,float或甚至是numpy浮点数: int('555555555555555555555')float('555555555555555555555')np.float('555555555555555555555') 但是,当我使用pandas函数pd.to_numeric时,
假设我在字符串中有一个大数字,例如’555555555555555555555′.可以选择将其转换为int,float或甚至是numpy浮点数:

int('555555555555555555555')
float('555555555555555555555')
np.float('555555555555555555555')

但是,当我使用pandas函数pd.to_numeric时,出现问题:

pd.to_numeric('555555555555555555555')

有错误:

Traceback (most recent call last):
  File "pandas/_libs/src/inference.pyx",line 1173,in pandas._libs.lib.maybe_convert_numeric
ValueError: Integer out of range.

During handling of the above exception,another exception occurred:

Traceback (most recent call last):
  File "C:path_to_condalibsite-packagesIPythoncoreinteractiveshell.py",line 3267,in run_code
    exec(code_obj,self.user_global_ns,self.user_ns)
  File "<ipython-input-34-6a735441ab7b>",line 1,in <module>
    pd.to_numeric('555555555555555555555')
  File "C:path_to_condalibsite-packagespandascoretoolsnumeric.py",line 133,in to_numeric
    coerce_numeric=coerce_numeric)
  File "pandas/_libs/src/inference.pyx",line 1185,in pandas._libs.lib.maybe_convert_numeric
ValueError: Integer out of range. at position 0

出了什么问题?为什么pandas to_numeric不能处理更大的值?是否有任何用例可以使用pd.to_numeric而不是像np.float这样的函数?

解决方法

因为您的数字大于系统能够保存的整数的最大大小:

In [4]: import sys

In [5]: sys.maxsize
Out[5]: 9223372036854775807

In [6]: 555555555555555555555 > sys.maxsize
Out[6]: True

以下是引发ValueError的the source code的一部分:

if not (seen.float_ or as_int in na_values):
    if as_int < oINT64_MIN or as_int > oUINT64_MAX:
        raise ValueError('Integer out of range.')

如您所见,因为您的数字不是浮点数,所以它将其视为整数并检查该数字是否在适当的范围oINT64_MIN,oUINT64_MAX.如果您通过了一个浮点数而不是它给了您正确的结果:

In [9]: pd.to_numeric('555555555555555555555.0')
Out[9]: 5.5555555555555554e+20

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读