【问题标题】:TypeError: unhashable type: 'list' when use groupby in pythonTypeError: unhashable type: 'list' 在 python 中使用 groupby 时
【发布时间】:2017-11-05 03:10:53
【问题描述】:

我使用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'。 我想按年和月分组,然后计算平均值,为什么会出错?

【问题讨论】:

    标签: python python-2.7 pandas pandas-groupby


    【解决方案1】:

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

    【讨论】:

    • 你也可以使用operator.attrgetter:key = operator.attrgetter('year', 'month')
    【解决方案2】:

    先将列表转换为 str,然后再将其用作 groupby 键。

    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
    

    【讨论】:

    猜你喜欢
    • 2022-12-05
    • 2015-02-11
    • 2020-05-11
    • 2021-03-14
    • 1970-01-01
    • 1970-01-01
    • 2019-10-11
    • 2020-03-27
    • 1970-01-01
    相关资源
    最近更新 更多