Python 错误 OverflowError: Python Int Too Large to Convert to C Long
本篇文章将介绍 Python 中的 OverflowError: python int too large to convert to c long 错误。
Python 错误OverflowError: python int too large to convert to c long
当算术结果超出数据类型的给定限制时,Python 中会引发 OverflowError。 我们遇到此指定错误是因为我们尝试使用大于给定范围的整数值进行操作。
代码:
import numpy as np
arr = np.zeros((1, 2), dtype=int)
a = [6580225610007]
arr[0] = a
输出:
OverflowError: Python int too large to convert to C long
上面的例子创建了一个 int 类型的数组。 我们尝试存储一个包含大于 int 类型范围的整数的列表。
还可以使用 sys 库中的常量检查最大大小。 该常量作为 sys.maxsize 可用。
修复Python中 OverflowError: Python int too large to convert to C long 错误
为了避免这个错误,我们必须注意我们可以使用 int 类型的最大范围。 存在一个修复程序,尤其是在这个关于 numpy 数组的示例中。
int 类型等同于 C 语言的 long int 类型,在 Python 3 中被改变,int 类型被转换为任意精度类型。
但是,numpy 库仍然按照 Python 2 中声明的方式使用它。long int 通常是平台相关的,但对于 windows,它始终是 32 位的。
要修复此错误,我们可以使用不依赖于平台的其他类型。 最常见的替代方案是 np.int64 类型,我们在数组中使用 dtype 参数指定它。
代码:
import numpy as np
arr = np.zeros((1, 2), dtype=np.int64)
a = [6580225610007]
arr[0] = a
print(arr)
输出:
[[6580225610007 6580225610007]]
上面的示例显示错误已使用替代类型解决。
另一种方法是使用 try 和 except 块。 这两个块用于解决 Python 中的异常。
如果 try 块中抛出异常,则执行 except 块中的代码。
代码:
import numpy as np
arr = np.zeros((1, 2), dtype=int)
a = [6580225610007]
try:
arr[0] = a
except:
print("Error in code")
输出:
Error in code
上面的示例使用 try 和 except 块避免了错误。
请记住
,这不是对给定错误的修复,而是一种解决错误的方法。
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串