Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 306
littlely Avatar asked Jun 04 '17 03:06

littlely


2 Answers

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()
like image 50
falsetru Avatar answered Nov 14 '22 10:11

falsetru


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
like image 6
Allen Avatar answered Nov 14 '22 08:11

Allen