gpt4 book ai didi

python - 在 Pandas 中使用多处理读取 csv 文件的最简单方法

转载 作者:太空狗 更新时间:2023-10-29 22:03:29 26 4
gpt4 key购买 nike

这是我的问题。
一堆 .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 运行它们来解决我的问题?
任何建议将不胜感激!

最佳答案

使用:

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()

关于python - 在 Pandas 中使用多处理读取 csv 文件的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36587211/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com