代码之家  ›  专栏  ›  技术社区  ›  FLab

熊猫系列:替换空列表时的最大递归错误

  •  1
  • FLab  · 技术社区  · 6 年前

    我有一只熊猫 Series 包含列表我想用 NaN 是的。 我的第一个方法是 .replace 但是,这意外地给了我一个最大的递归错误:

    import numpy as np
    import pandas as 
    ts = pd.Series([[1], [2, 3], [], [4]])
    ts.replace([], np.nan)
    
    RuntimeError: maximum recursion depth exceeded in comparison
    

    我用

    ts[ts.apply(len) == 0] = np.nan
    

    但有谁能帮我理解为什么 .替换 接近失败?

    2 回复  |  直到 6 年前
        1
  •  2
  •   GeorgPoe    6 年前

    从熊猫文件:

    Series.replace(to_replace=None, value=None,...)
    
    to_replace : str, regex, list, dict, Series, int, float, or None
    
    list of str, regex, or numeric:    
    - First, if to_replace and value are both lists, they must be the same length.
    - Second, if regex=True then all of the strings in both lists will be interpreted as regexs otherwise they will match directly. This doesn’t matter much for value since there are only a few possible substitution regexes you can use.
    - str, regex and numeric rules apply as above.
    

    pandas会将to_replace值[]误认为是要匹配的字符串列表,它试图替换其内容,而不是空列表本身。这会导致错误(因此,无论replace函数在这种情况下做什么,它都不会对空列表起作用—op的代码片段在我的环境中不起作用,但我得到了一条不同的错误消息。)

        2
  •  2
  •   John Zwinck    6 年前

    这样效率更高,工作正常:

    ts[ts.str.len() == 0] = np.nan
    

    你也许会想 ts.str 给你绳子,那不是它能做的全部!当序列包含列表时, .str 访问器仍然支持切片, len() ,等等--它们的意思只是与序列包含字符串时略有不同。所以 .str段 对于操作一系列列表非常有用。