代码之家  ›  专栏  ›  技术社区  ›  cs95 abhishek58g

熊猫表现出违反直觉的行为

  •  14
  • cs95 abhishek58g  · 技术社区  · 7 年前

    给定一系列

    s = pd.Series([1.1, 1.2, np.nan])
    s
    0    1.1
    1    1.2
    2    NaN
    dtype: float64
    

    如果需要将NAN转换为None(例如,使用镶木地板),那么我希望

    0     1.1
    1     1.2
    2    None
    dtype: object
    

    我想 Series.replace 这是一种显而易见的方法,但函数返回的结果如下:

    s.replace(np.nan, None)
    
    0    1.1
    1    1.2
    2    1.2
    dtype: float64
    

    NaN是向前填充的,而不是被替换。通过 docs ,我知道如果第二个参数是None,那么第一个参数应该是字典。基于此,我认为 replace 按预期替换,或引发异常。

    我相信这里的解决办法是

    pd.Series([x if pd.notna(x) else None for x in s], dtype=object) 
    0     1.1
    1     1.2
    2    None
    dtype: object
    

    这很好。但我想了解为什么会发生这种行为,不管它是有记录的,还是只是一个bug,我必须清理我的git配置文件并将其记录在问题跟踪器上。。。有什么想法吗?

    1 回复  |  直到 7 年前
        1
  •  7
  •   Dani Mesejo    4 年前

    该行为记录在 method 参数:

    method : {‘pad’, ‘ffill’, ‘bfill’, None}
    
    The method to use when for replacement, when to_replace is a scalar, list or tuple and value is None.
    

    在你的例子中 to_replace 是一个 标量 value None 。默认情况下,该方法为 pad ,摘自 fillna :

    pad / ffill: propagate last valid observation forward to next valid