"OverflowError: Python int too large to convert to C long" Windows 上,但不是 Mac 上的



我在Windows和Mac上运行完全相同的代码,使用python 3.5 64位。

在窗口上,它看起来像这样:

>>> import numpy as np
>>> preds = np.zeros((1, 3), dtype=int)
>>> p = [6802256107, 5017549029, 3745804973]
>>> preds[0] = p
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    preds[0] = p
OverflowError: Python int too large to convert to C long

但是,此代码在我的Mac上工作正常。任何人都可以帮助解释原因或为 Windows 上的代码提供解决方案吗?非常感谢!

您可以使用

dtype=np.int64而不是dtype=int

一旦您的数字大于 sys.maxsize,您就会收到该错误:

>>> p = [sys.maxsize]
>>> preds[0] = p
>>> p = [sys.maxsize+1]
>>> preds[0] = p
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: Python int too large to convert to C long

您可以通过检查来确认这一点:

>>> import sys
>>> sys.maxsize
2147483647

若要获取更高精度的数字,请不要在后台传递使用有界 C 整数的 int 类型。使用默认浮点数:

>>> preds = np.zeros((1, 3))

谁能帮忙解释为什么

Numpy 数组通常* 具有固定大小的元素,包括各种大小的整数、单精度或双精度浮点数、固定长度字节和 Unicode 字符串以及由上述类型构建的结构。

在Python 2中,python"int"相当于C长。在 Python 3 中,"int"是任意精度类型,但 numpy 在创建数组时仍然使用 "int" 来表示 C 类型"long"。

C 长的大小取决于平台。在窗口上,它始终是 32 位的。在类 Unix 系统上,它在 32 位系统上通常是 32 位,在 64 位系统上通常是 64 位。

或者为 Windows 上的代码提供解决方案?非常感谢!

选择大小不依赖于平台的数据类型。您可以在以下位置找到该列表 https://docs.scipy.org/doc/numpy/reference/arrays.scalars.html#arrays-scalars-built-in 最明智的选择可能是 np.int64

* Numpy 确实允许 python 对象数组,但我认为它们没有被广泛使用。

转换为浮点数:

import pandas as pd
df = pd.DataFrame()
l_var_l = [8258255190131389999999000003296, 50661]
df['temp'] = l_var_l
df['temp'] = df['temp'].astype(int)

以上失败并显示错误:

OverflowError: Python int too large to convert to C long.

现在尝试使用浮点转换:

df['temp'] = df['temp'].astype(float)

我在尝试将对象类型列(实际上是字符串)转换为整数类型时遇到了同样的错误。

这不起作用:

df['var1'] = df['var1'].astype(int)

这奏效了:

df['var1'] = df['var1'].apply(lambda x: int(x))

相关内容

最新更新