【问题标题】:pandas groupby column to sum the Counter performancepandas groupby 列对 Counter 性能求和
【发布时间】:2018-03-05 07:05:08
【问题描述】:

我有一个数据框,类似于:

index     name     message_counter
1         AA       Counter({'hello':1})
2         BB       Counter({'how':1, 'are':1, 'you':1})
3         BB       Counter({'how':1})
4         AA       Counter({'hello':1})
5         CC       Counter({'hello':1})

我想要每个唯一名称的所有计数器的总和。 所以我做了:

df.groupby('name')['message_counter'].sum()

并得到了正确的答案。类似:

name
AA            {'hello':2}
BB            {'how':2, 'are':1, 'you':1}
CC            {'hello':1}

但在我的数据集上它出奇地慢。它经历了 6 个独特的名称,并通过 33,000 个计数器(我的数据框中的行数)求和,这并不多,但我花费的时间比我预期的要长。大约 50 多秒,整个 180 行并不需要那么多时间。

我做错了什么?我该如何改进?

【问题讨论】:

    标签: python pandas dataframe counter pandas-groupby


    【解决方案1】:

    尝试使用稍微改进的this solution

    from collections import defaultdict
    
    def dsum(*dicts):
        ret = defaultdict(int)
        #add loop for Series of dicts
        for x in dicts:
            for d in x:
                for k, v in d.items():
                    ret[k] += v
        return dict(ret)
    
    df1 = df.groupby('name')['message_counter'].agg(dsum)
    

    【讨论】:

    • 哇是的表现好多了。知道为什么吗?
    • @sheldonzy - 在我看来pandas 对非标量值的工作速度不是很快,因为它不支持主要的(某些函数也应该失败),所以最好使用纯 python。
    猜你喜欢
    • 2018-04-14
    • 2021-05-24
    • 2015-06-21
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 2018-01-07
    • 2019-09-08
    • 2021-08-12
    相关资源
    最近更新 更多