python - 类型错误 : unhashable type: 'list' when use groupby in python

标签 python python-2.7 pandas pandas-groupby

使用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/

相关文章:

Python:我可以使用 urllib 导入 json 文件的切片吗?

python - 为什么 NumPy 数组优于标准库数组?

python - 完全卸载 Django

python - 使用 PPID 创建文件

python - 使用 pandas : TypeError: <class 'list' > is not convertible to datetime 将字符串转换为日期时间

python - pandas 滚动窗口意味着 future

python - 如何删除 XML 元素而不删除元素尾部的内容?

python - 将数组转换为百分位数

python - 如何使用 python 加速最近邻搜索?

python-2.7 - 显示/打印 Pandas 系列 DataFrame 中的一列