pandas 类型错误:“系列”对象是可变的,因此它们不能被列散列问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50450672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:34:58  来源:igfitidea点击:

TypeError: 'Series' objects are mutable, thus they cannot be hashed problemwith column

pythonpandas

提问by Corentin Moreau

I have a problem with a column of my dataframe but I don't understand why there are trouble on my column cat.enter image description here

我的数据框列有问题,但我不明白为什么我的列 cat 出现问题。在此处输入图片说明

enter image description here

在此处输入图片说明

回答by jpp

Your series contains other pd.Seriesobjects. This is bad practice. In general, you should ensure your series is of a fixed type to enable you to perform manipulations without having to check for typeexplicitly.

您的系列包含其他pd.Series对象。这是不好的做法。通常,您应该确保您的系列是固定类型,以便您无需type明确检查即可执行操作。

Your error is due to pd.Seriesobjects not being hashable. One workaround is to use a function to convert pd.Seriesobjects to a hashable type such as tuple:

您的错误是由于pd.Series对象不可散列。一种解决方法是使用函数将pd.Series对象转换为可散列类型,例如tuple

s = pd.Series(['one string', 'another string', pd.Series([1, 2, 3])])

def converter(x):
    if isinstance(x, pd.Series):
        return tuple(x.values)
    else:
        return x

res = s.apply(converter).unique()

print(res)

['one string' 'another string' (1, 2, 3)]