And*_* L. 3 python pandas python-3.6
我在python 3.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
Run Code Online (Sandbox Code Playgroud)
to_numeric与 errors='coerce'
pd.to_numeric(s, errors='coerce')
Out[37]:
0 10.0
1 12.0
2 15.0
3 20.0
4 NaN
5 31.0
6 NaN
7 NaN
dtype: float64
Run Code Online (Sandbox Code Playgroud)
to_numeric与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
Run Code Online (Sandbox Code Playgroud)
to_numeric与errors='ljljalklag'。即,随机字符串
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
Run Code Online (Sandbox Code Playgroud)
换句话说,传递任何串除了字符串raise,ignore对errors参数的pd.to_numeric相当于errors='coerce'。
这是功能还是错误?
AFAIK,鉴于源代码,这是预期的行为:
# pandas/core/tools/numeric.py
...
coerce_numeric = errors not in ("ignore", "raise") # line 147
...
Run Code Online (Sandbox Code Playgroud)
因此,仅检查是否errors为raise或ignore,否则coerce为默认值。
这已在版本 0.25.0 中修复以验证errors关键字(请参阅#26394)。
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
Run Code Online (Sandbox Code Playgroud)
0.24.2 中的先前行为:
In [1]: import pandas as pd; pd.__version__
Out[1]: '0.24.2'
In [2]: pd.to_numeric([1, 'a', 2.2], errors='foo')
Out[2]: array([1. , nan, 2.2])
Run Code Online (Sandbox Code Playgroud)