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

littlely picture littlely · Jun 4, 2017 · Viewed 10.9k times · Source

There is something wrong when I use groupby method:

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?

Answer

falsetru picture falsetru · Jun 4, 2017

list object cannot be used as key because it's not hashable. You can use tuple object instead:

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