Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/kubernetes/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 如何使用多处理从python中的数据帧创建gzip文件_Arrays_Python 3.x_Multithreading - Fatal编程技术网

Arrays 如何使用多处理从python中的数据帧创建gzip文件

Arrays 如何使用多处理从python中的数据帧创建gzip文件,arrays,python-3.x,multithreading,Arrays,Python 3.x,Multithreading,我有一个进程正在成为IO绑定,我将一个大型数据集从数据库拉到一个pandas数据帧中,然后尝试逐行处理,然后保存到一个gzip文件。我试图找到一种使用多处理的方法,能够将gzip的创建拆分为多个进程,然后将它们合并到一个文件中。或在不覆盖前一个线程的情况下并行处理。我找到了这个包p_tqdm,但我遇到了EOF问题,可能是因为线程相互覆盖。以下是我当前解决方案的示例: from p_tqdm import p_map df = pd.read_sql(some_sql, engine) thin

我有一个进程正在成为IO绑定,我将一个大型数据集从数据库拉到一个pandas数据帧中,然后尝试逐行处理,然后保存到一个gzip文件。我试图找到一种使用多处理的方法,能够将gzip的创建拆分为多个进程,然后将它们合并到一个文件中。或在不覆盖前一个线程的情况下并行处理。我找到了这个包p_tqdm,但我遇到了EOF问题,可能是因为线程相互覆盖。以下是我当前解决方案的示例:

from p_tqdm import p_map

df = pd.read_sql(some_sql, engine)
things =[]
for index, row in df.iterrows():
    things.append(row)    
p_map(process, things)

def process():
    with gzip.open("final.gz", "wb") as f:
        value = do_somthing(row)
        f.write(value.encode())

我不知道关于
p\u tqdm
的问题,但是如果我理解你的问题,那么使用
多处理
可能很容易做到

像这样的

import multiprocessing

def process(row):
    # take care that "do_somthing" must return class with encode() method (e.g. string)
    return do_somthing(row)

df = pd.read_sql(some_sql, engine)
things =[]
for index, row in df.iterrows():
    things.append(row)


with gzip.open("final.gz", "wb") as f, multiprocessing.Pool() as pool:
    for processed_row in pool.imap(process, things):
        f.write(processed_row.encode())
只有几条旁注:

  • pandas
    iterrows
    方法很慢-如果可能,请避免(请参阅)

  • 另外,您不需要创建
    东西
    ,只需将iterable传递给
    imap
    (甚至可以直接传递df.iterrows())即可节省一些内存

  • 最后,既然您似乎正在读取sql数据,为什么不直接连接到db并从
    SELECT…
    query在光标上迭代,同时跳过
    pandas


感谢您的回答和深思熟虑的评论。在进一步研究之后,我还意识到iterrows()在性能上是一场噩梦。我将我的数据帧更改为dask数据帧,然后将df.to_array()传递给它,然后对其进行迭代以生成.gz文件。性能要好得多。我想知道将df.array()传递到多处理池是否会更好。我对阅读SQL表很好奇——我不想影响DBs的性能,但我想加快这一部分的速度。现在我基本上做了一个fetchall,然后在数百万行上盲目地等待10秒。有什么提示吗?如我所说,直接在游标对象上迭代。您不会说您正在使用的db引擎是什么,但是,例如,如果它类似于sql,则通常可以这样做:
cur.execute(“SELECT*FROM x”)
然后对cur中的行执行
:…
。(该行通常是一个数据元组。)检查例如。我认为多重处理不会给您带来很多性能改进(它有相当大的开销),但这取决于您的用例。