【问题标题】:Why pd.to_numeric `errors=''` is equivalent to `errors='coerce'`为什么 pd.to_numeric `errors=''` 等价于 `errors='coerce'`
【发布时间】:2019-12-08 17:19:23
【问题描述】:

我在 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

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

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

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

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

这是功能还是错误?

【问题讨论】:

    标签: python pandas python-3.6


    【解决方案1】:

    AFAIK,这是预期的行为,因为源代码:

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

    所以它只检查errorsraise 还是ignore,否则默认为coerce

    【讨论】:

    • 只是熊猫的东西。 ://
    • 这不准确,因为它没有考虑到第 111-112 行发生的检查。
    • 正如@root 指出的那样,这是一个错误(可能是故意的错误),所以我接受了他的回答以正确反映这个问题。不过仍然赞成。
    【解决方案2】:

    此问题已在 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])
    

    【讨论】:

    • 哈,确实是个bug。我接受并赞成这个答案。
    猜你喜欢
    • 2021-08-06
    • 1970-01-01
    • 2016-12-12
    • 1970-01-01
    • 2016-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-09
    相关资源
    最近更新 更多