python如何正确使用asyncio和pandas读取csv

2024-05-03 12:49:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我在路径中有很多csv文件,我希望用pandas read_csv来读取, 然后使用熊猫海螺要合并所有返回的数据帧

但我认为我没有正确使用asyncio,因为时间消耗没有缩短。在

import asyncio
import time
import pandas as pd
import glob2
import os

async def read_csv(filename):
    df = pd.read_csv(filename, header=None)
    return df
t = time.time()
path = r'C:\LRM_STGY_REPO\IB_IN'

tasks = [asyncio.ensure_future(read_csv(i)) for i in list(glob2.iglob(os.path.join(path, "*.txt")))]

loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))

df = pd.concat([t.result() for t in tasks],ignore_index=True)
# print(df)
print( '%.4f' %(time.time()-t))

t = time.time()
def read_csv2(filename):
    return pd.read_csv(filename, header=None)
df = pd.concat(map(read_csv2,glob2.iglob(os.path.join(path, "*.txt"))),ignore_index=True)
# print(df)
print( '%.4f' %(time.time()-t))

read_csv和read_csv2的消耗时间相似。在

或者有其他的方法来减少concat时间。在


Tags: csvpathimportloopasynciodfreadtime