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

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

使用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()

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

list 对象不能用作键,因为它不可哈希。您可以改用 tuple 对象:

>>> {[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()

先将列表转换为 str,然后再将其用作 groupby 键。

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