pandas TypeError: unhashable type: 'list' 在 python 中使用 groupby 时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44350401/
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 03:43:37  来源:igfitidea点击:

TypeError: unhashable type: 'list' when use groupby in python

pythonpython-2.7pandaspandas-groupby

提问by littlely

There is something wrong when I use groupby method:

当我使用 groupby 方法时出现问题:

data = pd.Series(np.random.randn(100),index=pd.date_range('01/01/2001',periods=100))
keys = lambda x: [x.year,x.month]
data.groupby(keys).mean()

but it has an error: TypeError: unhashable type: 'list'. I want group by year and month, then calculate the means,why it has wrong?

但它有一个错误:TypeError: unhashable type: 'list'。我想按年和月分组,然后计算平均值,为什么会出错?

回答by falsetru

listobject cannot be used as key because it's not hashable. You can use tupleobject instead:

list对象不能用作键,因为它不可散列。您可以使用tupleobject 代替:

>>> {[1, 2]: 3}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> {(1, 2): 3}
{(1, 2): 3}


data = pd.Series(np.random.randn(100), index=pd.date_range('01/01/2001', periods=100))
keys = lambda x: (x.year,x.month)  # <----
data.groupby(keys).mean()

回答by Allen

Convert the list to a str first before using it as groupby keys.

在将列表用作 groupby 键之前,先将其转换为 str 。

data.groupby(lambda x: str([x.year,x.month])).mean()
Out[587]: 
[2001, 1]   -0.026388
[2001, 2]   -0.076484
[2001, 3]    0.155884
[2001, 4]    0.046513
dtype: float64