【发布时间】:2018-01-23 14:08:37
【问题描述】:
我正在尝试使用pandas.to_numeric 将系列转换为ints。
df['numeric_col'] = pd.to_numeric(df['numeric_col'], errors='raise')
我遇到了错误,
Traceback (most recent call last):
File "/home/user_name/script.py", line 86, in execute
data = module(**module_args).execute(data)
File "/home/user_name/script.py", line 62, in execute
invoices['numeric_invoice_no'] = pd.to_numeric(invoices['numeric_invoice_no'], errors='raise')
File "/usr/local/lib/python3.5/dist-packages/pandas/core/tools/numeric.py", line 126, in to_numeric
coerce_numeric=coerce_numeric)
File "pandas/_libs/src/inference.pyx", line 1052, in pandas._libs.lib.maybe_convert_numeric (pandas/_libs/lib.c:56638)
ValueError: Integer out of range. at position 106759
如果我改成,
df['numeric_col'] = pd.to_numeric(df['numeric_col'], errors='coerce')
numeric_col 中的值不会转换为ints,即它们仍然是strings。
如果我改成,
df['numeric_col'] = df['numeric_col'].astype(int)
我有错误,
OverflowError: Python int too large to convert to C long
所以我必须把它改成,
df['numeric_col'] = df['numeric_col'].astype(float)
然后没有产生错误。
系列的大小约为994572,列中的字符串如52333612273、56032860或02031757。
我想知道这里的to_numeric 和astype 有什么问题。
我在Linux mint 18.1 64-bit 上运行Python 3.5。
【问题讨论】:
-
您的某些值超出了 64 位整数的限制,因此会出现错误。你打算用这些值做什么
-
@EdChum 我打算做一些简单的算术运算,所以转换为
float也可以,但只是想知道为什么转换int不起作用。 -
您的值是否超过了64-bit int 的数值限制?
-
通过
np.finfo('float64').max和np.iinfo('int64').max检查最大值。整数的最大值要小得多。 -
@EdChum 只是不清楚是哪个值,有没有办法排除超出限制的值,或者定位到值,它在哪里
标签: python-3.x pandas numpy dataframe series