【问题标题】:iterating through hundreds of thousands of csv files with pandas使用 pandas 遍历数十万个 csv 文件
【发布时间】:2018-02-15 13:29:18
【问题描述】:

我目前正在使用 concurrent.futures.ProcessPoolExectutor 来遍历大量 CSV 文件,如下所示:

def readcsv(file):
    df = pd.read_csv(file, delimiter="\s+", names=[headers], comment="#")
    #DOING SOME OTHER STUFF TO IT 
    full.append(df) 

if __name__ == "__main__":
    full = []
    files = "glob2 path to files" 
    with concurrent.futures.ProcessPoolExecutor(max_workers=45) as proc:
        proc.map(readcsv,files)
    full = pd.concat(full)

这目前不能以这种方式工作,因为它在最后一行返回一个 ValueError "No Objects to concatenate"。如何遍历文件并将它们附加到列表中,然后将它们连接起来,或者尽快将它们直接放入数据框中?可用资源是虚拟机中的 64gb 内存和 46 个内核。

【问题讨论】:

  • 你看过dask - 它会为你做这些...df = dask.dataframe.read_csv('*.csv').compute()....如果你把计算拿掉,你也可以在阅读和如果您不需要一次所有内存中的数据并且只想总结一列等,请将它们拼凑在一起......

标签: python multithreading python-3.x pandas multiprocessing


【解决方案1】:

map 函数实际上是 returns an iterable 以及函数的结果。所以你只需要返回df:

def readcsv(file):
    df = pd.read_csv(file, delimiter="\s+", names=[headers], comment="#")
    #DOING SOME OTHER STUFF TO IT 
    return df

if __name__ == "__main__":
    files = "glob2 path to files" 
    with concurrent.futures.ProcessPoolExecutor(max_workers=45) as proc:
        full = pd.concat(proc.map(readcsv,files))

【讨论】:

    猜你喜欢
    • 2018-06-20
    • 1970-01-01
    • 1970-01-01
    • 2013-04-23
    • 2014-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-21
    相关资源
    最近更新 更多