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

Python 熊猫系列:替换空列表时的最大递归错误,python,pandas,Python,Pandas,我有一个包含列表的熊猫系列。我想用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(l

我有一个包含列表的熊猫系列。我想用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方法失败的原因吗?

这更有效,而且工作正常:

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

虽然您可能认为ts.str提供了字符串,但这并不是它所能做的全部!当一个序列包含列表时,.str访问器仍然支持切片、len等,它们的意思与序列包含字符串时略有不同。因此.str对于在一系列列表上操作非常有用。

这更有效,并且工作正常:

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

虽然您可能认为ts.str提供了字符串,但这并不是它所能做的全部!当一个序列包含列表时,.str访问器仍然支持切片、len等,它们的意思与序列包含字符串时略有不同。因此.str对于操作一系列列表非常有用。

来自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值[]误认为是要匹配的字符串列表,它试图替换其内容,而不是空列表本身。这会导致错误。因此,无论replace函数在这种情况下做什么,它都不会对空列表起作用-OP的代码片段在我的环境中不起作用,但我会收到不同的错误消息。

来自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值[]误认为是要匹配的字符串列表,它试图替换其内容,而不是空列表本身。这会导致错误。因此,无论replace函数在这种情况下做什么,它都不会对空列表起作用-OP的代码片段在我的环境中不起作用,但我会收到不同的错误消息。

在0.23.1中,我得到内核死机,在anaconda中重新启动,这看起来像是一个bug,因为你可以在pandas replace函数中传递一个列表作为替换参数,它假设你传递的是一个要替换的值列表。当这个列表为空时,它可能会失败。我认为这是一个主要的一般性问题-糟糕。/错误地使用系列中的非标量值的函数:我建议在这里提交这个问题:在0.23.1中,我导致内核死机,在anaconda中重新启动,这看起来像是一个bug,因为你可以在pandas replace函数中传递一个列表作为替换参数,它假设你传递的是一个要替换的值列表。当这个列表为空时,它可能会失败。我认为这是一个主要的一般性问题-糟糕的。/错误的使用系列中的非标量值的函数:我建议在这里提交这个问题:谢谢,解释是有意义的。我还向熊猫提交了一份虫子报告,我将等待他们确认。谢谢,解释是有意义的。我还向熊猫提交了一份虫子报告,我将等待他们确认