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?
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()
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With