littlely
littlely

Reputation: 1418

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

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?

Upvotes: 21

Views: 29479

Answers (2)

Allen Qin
Allen Qin

Reputation: 19947

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

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

Upvotes: 6

falsetru
falsetru

Reputation: 368954

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

Upvotes: 20

Related Questions