python - 在熊猫中并行化 groupby 和 agg 的有效方法
问题描述
我想并行化以下函数并加快 groupby 进程:
df = pd.DataFrame({'A': ['a', 'a', 'b', 'c', 'b', 'b'], 'B': ['e1', 'e1', 'e2', 'e3', 'e4', 'e2'], 'C':[[1,2,3], [4,1,5], [2,5,1], [6,2,6], [7,1,3], [7,5,8]]})
df = df.groupby(['A', 'B'], as_index=False).agg({'C': sum})
我尝试了以下并行功能,但它并没有减少所花费的时间:
from functools import partial
import multiprocessing as mp
import os
def applyParallel(dfGrouped, func, *args):
p=mp.Pool(os.cpu_count())
result=p.map(partial(func, *args), [group for name, group in dfGrouped])
p.close()
return(result)
def aggregate_fun(data):
data = data.groupby(['A', 'B'], as_index=False).agg({'C': sum})
return data
df1 = df.groupby(['A', 'B'], as_index=False)
df2 = applyParallel(df1, aggregate_fun)
df_grouped = pd.concat(df2, axis=0)
如何并行化或减少上述功能所花费的时间,我有大约 300 万行,这需要很多时间。
解决方案
当您仅使用单列时,您可以减少 groupby 请求的时间,例如:
import pandas as pd
df = pd.DataFrame({'A': ['a', 'a', 'b', 'c', 'b', 'b'], 'B': ['e1', 'e1', 'e2', 'e3', 'e4', 'e2'], 'C':[[1,2,3], [4,1,5], [2,5,1], [6,2,6], [7,1,3], [7,5,8]]})
df['new_col'] = df['A']+df['B']
df = df.groupby(['new_col'], as_index=False).agg({'C': sum})
处理时间 = 2.6 ms 而不是 ['A', 'B'] 的 3.5 ms 并且创建新列非常便宜(0.25 ms)。
推荐阅读
- firebase-realtime-database - 允许其他用户读取/写入数据 Firebase 数据库
- oracle - 如何知道我是否可以使用我的 oracle 用户删除?没有实际删除任何东西?
- php - 我无法安装 PHP
- javascript - React 和 Express 中的重定向/路由问题
- google-sheets - 选择 $M:$M 和 $N:$N 将返回“COUNTIFS 的数组参数大小不同”
- netty - 当请求被写入代理网络服务器中的 outboundChannel 时,如何在相同的处理程序中获取响应 byteBuf
- graphics - 如何界定趋势线的宽度?
- yaml - GatsbyJS:如何将数组存储在降价文件中?
- azure - 无法获取 Azure AD 用户组
- python-3.x - Python无法解码字节:无效的起始字节