.应用(pd.to_数字)返回错误消息

2024-03-29 12:38:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含两列的dataframe要转换为数值类型。我使用以下代码:

df[["GP","G"]]=df[["GP","G"]].apply(pd.to_numeric)

Python返回以下错误消息:

^{pr2}$

我怎样才能解决这个问题?如何使用命令同时转换多个列类型?谢谢您!在


Tags: to代码命令消息类型dataframedf错误
1条回答
网友
1楼 · 发布于 2024-03-29 12:38:16

只有当所有的数据都能被解析为数字时,你的代码才能工作。在

否则,dataframe中至少有一个值不能转换为数值。在这种情况下,可以根据您的选择使用errors参数。这里有一个例子。在

>>> df = pd.DataFrame({'A' : list('aabbcd'), 'B' : list('ffghhe')})

>>> df
   A  B
0  a  f
1  a  f
2  b  g
3  b  h
4  c  h
5  d  e

>>> df.apply(pd.to_numeric, errors='ignore')
   A  B
0  a  f
1  a  f
2  b  g
3  b  h
4  c  h
5  d  e

>>> df.apply(pd.to_numeric, errors='coerce')
    A   B
0 NaN NaN
1 NaN NaN
2 NaN NaN
3 NaN NaN
4 NaN NaN
5 NaN NaN

>>> df.apply(pd.to_numeric, errors='raise')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/pandas/core/frame.py", line 4042, in apply
    return self._apply_standard(f, axis, reduce=reduce)
  File "/usr/local/lib/python2.7/dist-packages/pandas/core/frame.py", line 4138, in _apply_standard
    results[i] = func(v)
  File "/usr/local/lib/python2.7/dist-packages/pandas/core/frame.py", line 4020, in f
    return func(x, *args, **kwds)
  File "/usr/local/lib/python2.7/dist-packages/pandas/tools/util.py", line 98, in to_numeric
    coerce_numeric=coerce_numeric)
  File "pandas/src/inference.pyx", line 612, in pandas.lib.maybe_convert_numeric (pandas/lib.c:53932)
  File "pandas/src/inference.pyx", line 598, in pandas.lib.maybe_convert_numeric (pandas/lib.c:53719)
ValueError: ('Unable to parse string', u'occurred at index A')
>>> 

以下是errors的文档

errors : {‘ignore’, ‘raise’, ‘coerce’}, default ‘raise’

If ‘raise’, then invalid parsing will raise an exception

If ‘coerce’,then invalid parsing will be set as NaN

If ‘ignore’, then invalid parsing will return the input

相关问题 更多 >