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

Gui*_*ido 3 python numpy pandas

假设我在一个字符串中有一个很大的数字,比如'555555555555555555555'.可以选择将其转换为int,float或甚至是numpy浮点数:

int('555555555555555555555')
float('555555555555555555555')
np.float('555555555555555555555')
Run Code Online (Sandbox Code Playgroud)

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

pd.to_numeric('555555555555555555555')
Run Code Online (Sandbox Code Playgroud)

有错误:

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_conda\lib\site-packages\IPython\core\interactiveshell.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_conda\lib\site-packages\pandas\core\tools\numeric.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
Run Code Online (Sandbox Code Playgroud)

出了什么问题?为什么大熊猫不能to_numeric处理更大的价值?是否有任何用例,为什么你会使用pd.to_numeric而不是像np.float

Kas*_*mvd 6

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

In [4]: import sys

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

In [6]: 555555555555555555555 > sys.maxsize
Out[6]: True
Run Code Online (Sandbox Code Playgroud)

以下是引发以下内容的源代码的一部分ValueError:

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.')
Run Code Online (Sandbox Code Playgroud)

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

In [9]: pd.to_numeric('555555555555555555555.0')
Out[9]: 5.5555555555555554e+20
Run Code Online (Sandbox Code Playgroud)

  • @ayhan我认为基于这[line](https://github.com/pandas-dev/pandas/blob/9ad1e00c5c70b4446f2af5bea9089ca3312a3eb5/pandas/_libs/lib.pyx#L1795),它将隐含地假设数组的类型数组中第一个值的类型 (2认同)
  • @ayhan这显然是一个不同的案例.在这里,您有多种类型,并且决定哪一个应该具有更高的优先级是一个与处理一个输入时不同的问题.似乎他们决定顺序但是我觉得这是错的.应该有更复杂的方法来优先考虑列表项. (2认同)
  • 是的,似乎你是对的,但基于这个顺序会导致非常奇怪的结果:`pd.to_numeric(['555555555555555555555','abc'],errors ='coerce')`vs`pd.to_numeric([' abc','555555555555555555555'],errors ='coerce')`.将来使用`to_numeric`时我会更加谨慎. (2认同)