python - 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")
我想我可以将该函数应用于数据帧的小样本,以防止内存错误,然后将它们组合起来,但我宁愿改进函数的计算时间。
解决方案
这个函数做同样的事情,而且快了 10 倍。
test.groupby(["year", "month"], as_index=False).agg({"day_count":sum}).rename(columns={"day_count":"month_count"})
推荐阅读
- math - 概率分布
- javascript - 如何将一串句子分成两半,分成两个字符串的数组,每个字符串的长度尽可能相似?
- javascript - 客户端 onTextChanged
- java - 如何在 Java 中使用 opencv 或 ffmpeg 在网络摄像头流上覆盖视频
- java - 如果我删除不管理此关联的实体,是否有办法让 Hibernate 处理删除 @ManyToMany 关联中的条目?
- lua - 错误 main.lua:98:尝试索引本地“e”(一个数值)
- c++ - Unix TCP socket send() 不能正确下载除 HTML 文件以外的任何其他文件?
- php - 如何从任何控制器 Laravel 5.7 访问模型内的变量?
- hive - 设置什么配置单元属性以避免交叉产品?
- unity3d - 在统一编辑器中,点光源没有亮度