为什么?pd.to_数字`errors=''`相当于'errors='forcet'`

2024-09-30 18:31:20 发布

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

我使用的是python3.7和pandas 0.24.2

设置:

s = pd.Series(['10', '12', '15', '20', 'A', '31', 'C', 'D'])

In [36]: s
Out[36]:
0    10
1    12
2    15
3    20
4     A
5    31
6     C
7     D
dtype: object

errors='coerce'输入数字

^{pr2}$

errors=''表示数字(空字符串)

pd.to_numeric(s, errors='')

Out[38]:
0    10.0
1    12.0
2    15.0
3    20.0
4     NaN
5    31.0
6     NaN
7     NaN
dtype: float64

errors='ljljalklag'输入数字。一、 随机e字符串

pd.to_numeric(s, errors='ljljalklag')

Out[39]:
0    10.0
1    12.0
2    15.0
3    20.0
4     NaN
5    31.0
6     NaN
7     NaN
dtype: float64

换句话说,将字符串raiseignore之外的任何字符串传递给pd.to_numericerrors参数等同于errors='coerce'。在

这是一个功能还是bug?在


Tags: to字符串inpandas数字nanoutseries
2条回答

如果源代码:

# pandas/core/tools/numeric.py
... 
coerce_numeric = errors not in ("ignore", "raise") # line 147
...

所以它只检查errorsraise还是{},否则{}是默认值。在

为了验证errors关键字(请参见#26394),已在0.25.0版本中修复了此问题。在

0.25.0中的新行为:

In [1]: import pandas as pd; pd.__version__
Out[1]: '0.25.0'

In [2]: pd.to_numeric([1, 'a', 2.2], errors='foo')
                                     -
ValueError: invalid error value specified

0.24.2中以前的行为:

^{pr2}$

相关问题 更多 >