python - Pandas 系列 : maximum recursion error when replacing empty lists

标签 python pandas

我有一个包含列表的 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/

相关文章:

python - 试图将多边形数据分成 x 和 y 坐标,但得到错误 "' MultiPolygon' 对象没有属性 'exterior'”

python - Pycharm - 在远程解释器中配置 PYTHONPATH

python - 将列表切片为最大字符串大小

python:xlsxwriter将数据框+公式添加到excel文件

python - 在Python中将多张Excel文件按一列拆分

python - 根据另一个数据帧列值将数据帧列和行合并到特定索引

python - 导入错误 : No module named 'psutil'

python - 在 sklearn 中使用留一法交叉验证的 ROC 曲线

python - 向每个组 pandas python 添加序列计数

python - Pandas/Python 根据条件添加行