【问题标题】:pandas to_numeric couldn't convert string values to integerspandas to_numeric 无法将字符串值转换为整数
【发布时间】: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,列中的字符串如523336122735603286002031757

我想知道这里的to_numericastype 有什么问题。

我在Linux mint 18.1 64-bit 上运行Python 3.5

【问题讨论】:

  • 您的某些值超出了 64 位整数的限制,因此会出现错误。你打算用这些值做什么
  • @EdChum 我打算做一些简单的算术运算,所以转换为float 也可以,但只是想知道为什么转换int 不起作用。
  • 您的值是否超过了64-bit int 的数值限制?
  • 通过np.finfo('float64').maxnp.iinfo('int64').max 检查最大值。整数的最大值要小得多。
  • @EdChum 只是不清楚是哪个值,有没有办法排除超出限制的值,或者定位到值,它在哪里

标签: python-3.x pandas numpy dataframe series


【解决方案1】:

也许您的数字字符串值中有一个逗号(,),或者您的数据框的列中仍然有一个空值(NaN),因此请尝试使用空格替换逗号 .replace() 方法 然后删除或填写 Null 值 .fillna() 或 .replace 或 .dropna()

使用前 df['DataFrame Column'] = df['DataFrame Column'].astype(int)

【讨论】:

  • 如果您需要来自 OP 的更多详细信息,您可以随时在问题的 cmets 中询问他们
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-22
  • 2015-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多