【问题标题】:Easiest way to read csv files with multiprocessing in Pandas在 Pandas 中使用多处理读取 csv 文件的最简单方法
【发布时间】:2016-08-03 21:19:44
【问题描述】:

这是我的问题。
带有一堆 .csv 文件(或其他文件)。 Pandas 是一种读取它们并保存为Dataframe 格式的简单方法。但是当文件量很大时,我想通过多处理读取文件以节省一些时间。

我的早期尝试

我手动将文件分成不同的路径。单独使用:

os.chdir("./task_1")
files = os.listdir('.')
files.sort()
for file in files:
    filename,extname = os.path.splitext(file)
    if extname == '.csv':
        f = pd.read_csv(file)
        df = (f.VALUE.as_matrix()).reshape(75,90)   

然后将它们组合起来。

如何使用pool 运行它们来解决我的问题?
任何建议将不胜感激!

【问题讨论】:

标签: python csv pandas multiprocessing


【解决方案1】:

使用Pool

import os
import pandas as pd 
from multiprocessing import Pool

# wrap your csv importer in a function that can be mapped
def read_csv(filename):
    'converts a filename to a pandas dataframe'
    return pd.read_csv(filename)


def main():

    # get a list of file names
    files = os.listdir('.')
    file_list = [filename for filename in files if filename.split('.')[1]=='csv']

    # set up your pool
    with Pool(processes=8) as pool: # or whatever your hardware can support

        # have your pool map the file names to dataframes
        df_list = pool.map(read_csv, file_list)

        # reduce the list of dataframes to a single dataframe
        combined_df = pd.concat(df_list, ignore_index=True)

if __name__ == '__main__':
    main()

【讨论】:

  • df_list 包含什么?
  • @serafeim df_list 是由进程池生成的pd.DataFrames 的列表。
  • 有没有什么情况下这段代码行不通?我试图改为读取 excel 文件,但有时它会卡住。
【解决方案2】:

dask 库旨在解决您的问题。

【讨论】:

    【解决方案3】:

    如果您不反对使用其他库,您可以使用Graphlab 的 sframe。这会创建一个类似于数据帧的对象,如果性能是一个大问题,它读取数据的速度非常快。

    【讨论】:

      【解决方案4】:

      我没有让 map/map_async 工作, 但设法使用 apply_async

      两种可能的方式(我不知道哪个更好):

      • A) 在结束连接
      • B) 连接期间

      我发现glob很容易列出fitler目录中的文件

      from glob import glob
      import pandas as pd
      from multiprocessing import Pool
      
      folder = "./task_1/" # note the "/" at the end
      file_list = glob(folder+'*.xlsx')
      
      def my_read(filename):
          f = pd.read_csv(filename)
          return (f.VALUE.as_matrix()).reshape(75,90)
      
      #DF_LIST = [] # A) end
      DF = pd.DataFrame() # B) during
      
      def DF_LIST_append(result):
          #DF_LIST.append(result) # A) end
          global DF # B) during
          DF = pd.concat([DF,result], ignore_index=True) # B) during
      
      pool = Pool(processes=8)
      
      for file in file_list:
          pool.apply_async(my_read, args = (file,), callback = DF_LIST_append)
      
      pool.close()
      pool.join()
      
      #DF = pd.concat(DF_LIST, ignore_index=True) # A) end
      
      print(DF.shape)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-15
        • 1970-01-01
        • 1970-01-01
        • 2017-03-10
        • 2019-03-18
        • 1970-01-01
        • 2020-12-13
        相关资源
        最近更新 更多