首页 > 解决方案 > Pandas 提高效率

问题描述

我有一个大约 300 万行的 pandas 数据框。我想根据另一个变量将最后一列部分聚合到不同的位置。

我的解决方案是根据该变量将数据框行分成新数据框列表,聚合数据框,然后将它们再次加入单个数据框。问题是在几十万行之后,我得到一个内存错误。我可以使用哪些方法来提高函数的效率以防止这些内存错误?

我的代码示例如下

test = pd.DataFrame({"unneeded_var": [6,6,6,4,2,6,9,2,3,3,1,4,1,5,9],
                     "year": [0,0,0,0,1,1,1,2,2,2,2,3,3,3,3], 
                     "month" : [0,0,0,0,1,1,1,2,2,2,3,3,3,4,4],
                     "day" : [0,0,0,1,1,1,2,2,2,2,3,3,4,4,5], 
                     "day_count" : [7,4,3,2,1,5,4,2,3,2,5,3,2,1,3]})
test = test[["year", "month", "day", "day_count"]]

def agg_multiple(df, labels, aggvar, repl=None):
    if(repl is None): repl = aggvar
    conds = df.duplicated(labels).tolist() #returns boolean list of false for a unique (year,month) then true until next unique pair
    groups = []
    start = 0
    for i in range(len(conds)): #When false, split previous to new df, aggregate count 
        bul = conds[i]
        if(i == len(conds) - 1): i +=1 #no false marking end of last group, special case
        if not bul and i > 0 or bul and i == len(conds): 
            sample = df.iloc[start:i , :]
            start = i
            sample = sample.groupby(labels, as_index=False).agg({aggvar:sum}).rename(columns={aggvar : repl})
            groups.append(sample)
    df = pd.concat(groups).reset_index(drop=True) #combine aggregated dfs into new df
    return df



test = agg_multiple(test, ["year", "month"], "day_count", repl="month_count")

我想我可以将该函数应用于数据帧的小样本,以防止内存错误,然后将它们组合起来,但我宁愿改进函数的计算时间。

标签: pythonperformancepandas

解决方案


这个函数做同样的事情,而且快了 10 倍。

test.groupby(["year", "month"], as_index=False).agg({"day_count":sum}).rename(columns={"day_count":"month_count"})

推荐阅读