【问题标题】:Python multiprocessing with dataframe and multiple arguments具有数据框和多个参数的 Python 多处理
【发布时间】:2017-12-07 14:25:42
【问题描述】:

根据this answer 应使用多参数starmap 的多处理。我遇到的问题是我的论点之一是一个常量数据框。当我创建要由我的函数和星图使用的参数列表时,数据框会一遍又一遍地存储。我虽然可以使用namespace 解决这个问题,但似乎无法弄清楚。我下面的代码没有抛出错误,但 30 分钟后没有文件写入。代码在 10 分钟内运行,不使用多处理,直接调用 write_file

import pandas as pd
import numpy as np
import multiprocessing as mp

def write_file(df, colIndex, splitter, outpath):
    with open(outpath + splitter + ".txt", 'a') as oFile:
        data = df[df.iloc[:,colIndex] == splitter]
        data.to_csv(oFile, sep = '|', index = False, header = False)

mgr = mp.Manager()
ns = mgr.Namespace()
df = pd.read_table(file_, delimiter = '|', header = None)
ns.df = df.iloc[:,1] = df.iloc[:,1].astype(str)
fileList = list(df.iloc[:, 1].astype('str').unique())
for item in fileList:
    with mp.Pool(processes=3) as pool:
        pool.starmap(write_file, np.array((ns, 1, item, outpath)).tolist())

【问题讨论】:

  • 您找到解决方案了吗?
  • 见下方答案

标签: python dataframe multiprocessing


【解决方案1】:

对于其他在这个问题上苦苦挣扎的人,我的解决方案是通过以下方式从数据帧中创建一个长度为 chunksize 的元组的可迭代列表:

iterable = product(np.array_split(data, 15), [args])

然后,将此迭代传递给星图:

pool.starmap(func, iterable)

【讨论】:

  • 在这种情况下 [args] 是什么?
猜你喜欢
  • 2017-03-24
  • 2018-04-03
  • 1970-01-01
  • 2015-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-24
  • 1970-01-01
相关资源
最近更新 更多