我有一个包含列表的 pandas 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
但是谁能帮我理解为什么 .replace
方法失败了?
最佳答案
来自 Pandas 文档:
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 值误认为是要匹配的字符串列表,它会尝试替换其内容而不是空列表本身。这会导致错误。 (因此无论替换函数在这种情况下做什么,它都不适用于空列表 - OP 的代码片段在我的环境中不起作用,但我收到了不同的错误消息。)
关于python - Pandas 系列 : maximum recursion error when replacing empty lists,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51421796/