簡體   English   中英

Windows上的“溢出錯誤:Python int太大而無法轉換為C long”,但不是Mac

[英]“OverflowError: Python int too large to convert to C long” on windows but not mac

我在 windows 和 mac 上運行完全相同的代碼,python 3.5 64 位。

在 Windows 上,它看起來像這樣:

>>> 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 上的代碼提供解決方案嗎? 非常感謝!

一旦您的數字大於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))

您可以使用dtype=np.int64而不是dtype=np.int64 dtype=int

誰能幫忙解釋一下原因

在 Python 2 中,python "int" 相當於 C long。 在 Python 3 中,“int”是一種任意精度類型,但 numpy 在創建數組時仍然使用“int”來表示 C 類型“long”。

C long 的大小取決於平台。 在 Windows 上,它始終是 32 位。 在類 Unix 系統上,通常在 32 位系統上為 32 位,在 64 位系統上為 64 位。

或為 Windows 上的代碼提供解決方案? 非常感謝!

選擇大小與平台無關的數據類型。 您可以在https://docs.scipy.org/doc/numpy/reference/arrays.scalars.html#arrays-scalars-built-in找到該列表,最明智的選擇可能是 np.int64

轉換為浮動:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM