使用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()
关于python - 类型错误 : unhashable type: 'list' when use groupby in python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44350401/