首页 > 解决方案 > 让 Python Pandas 更快

问题描述

我有下面的代码,它可以成功运行,用于解析、清理日志文件(非常大)并输出到更小的文件中。处理 1 GB 的日志(在我的笔记本电脑上)大约需要 12-14 分钟。这可以更快吗?Dask 或并行性或 asyncio 或其他有助于加快速度吗?

我是 python 和 pandas 的新手,我用谷歌搜索过,但我完全糊涂了,似乎无法采用我看到的任何例子。

请帮助改进此代码

for root, dirs, files in os.walk('.', topdown=True):
    for file in files:
        try:
            for df in pd.read_csv(file, sep='\n', header=None, engine='python', quoting=3, chunksize=1200000):
                df = df[0].str.strip(' \t"').str.split('[,|;: \t]+', 1, expand=True).rename(columns={0: 'email', 1: 'data'}) 

                mask = (df.email.str.contains(emailreg, regex=True, na=False)) & (~df.data.str.contains(asciireg, regex=True, na=False))
                df2 = df[~mask].copy()
                df = df[mask].copy()
                df2[['email', 'data']].to_csv("errorfile", sep=':', index=False, header=False, mode='a', compression='gzip')
                del df2
                del mask

                for x in "abcdefghijklmnopqrstuvwxyz0123456789":
                    df2 = df[df.email.str.startswith(x)]
                    if (df.email.size > 0):
                        df2[['email', 'data']].to_csv(x, sep=':', index=False, header=False, mode='a')

示例日志文件

"email1@foo.com:datahere2     
email2@foo.com:datahere2
email3@foo.com datahere2
email5@foo.com;dtat'ah'ere2 
wrongemailfoo.com
email3@foo.com:datahere2

标签: pythonpandaspython-asynciodask

解决方案


推荐阅读