我在吃蟒蛇3.7和熊猫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: objectto_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带有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: float64to_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换句话说,除了字符串raise,ignore传递给pd.to_numeric的errors参数以外的任何字符串都等同于errors='coerce'。
这是一个或几个bug吗?
发布于 2019-07-31 18:28:53
在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在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])发布于 2019-07-31 08:38:33
AFAIK,这是意图行为,考虑到源代码:
# pandas/core/tools/numeric.py
...
coerce_numeric = errors not in ("ignore", "raise") # line 147
...因此,它只检查errors是raise还是ignore,或者是默认的coerce。
https://stackoverflow.com/questions/57286501
复制相似问题