首页 > 解决方案 > 有没有更好的方法来提高 concat 速度?

问题描述

我是韩国的学生,我正在使用 python 来分析期权数据(金融)。我正在寻找一种更好的方法来加快我的 python 代码的性能。

目标数据为期权的交易记录(每分钟),时间段为2015年至2019年。由于数据分为1227(5年内的工作日数)文件(txt),我尝试将所有1227文件串联尽量减少访问内存的次数。这是因为我将重复使用结果文件(连接文件 = 预处理文件)并且访问每个分离的文件花费了太多时间。下面是我的代码的一部分。

#file_name is list type and it contains all names of the 1227 day files ordered by date

result_df = pd.DataFrame()
for f in file_name: 

    data_opt = pd.read_csv(location + f, header = None, sep = "\t")

    #do something
    #...
    #...

    oneday_df = pd.concat([minute_call, minute_put], axis = 0) #result of the processing one day data

    result_df = pd.concat([result_df, oneday_df], axis = 0)

result_df.to_csv()

此代码有效,我可以获得正确的结果。但是,我可以看到随着时间的推移速度变慢了。这意味着我的代码在处理早期数据时运行速度很快,但在处理后期数据时速度变慢。有没有更好的方法来加快我的 python 代码的性能?

(对不起我笨拙的英语,感谢您阅读所有问题)

标签: pythonpandasperformanceconcatenation

解决方案


与其在内存中连接,不如保持输出 CSV 文件打开并在执行过程中分别将每个部分写入其中?

这样,您一次在内存中的数据量永远不会超过一天,不仅可以提高速度,还可以提高内存消耗。

就像是:

with open('out_file.csv', 'w') as of:
    for i, f in enumerate(file_name): 

        data_opt = pd.read_csv(location + f, header = None, sep = "\t")

        #do something
        #...
        #...

        oneday_df = pd.concat([minute_call, minute_put], axis = 0) #result of the processing one day data

        is_first_part = (i == 0)
        oneday_df.to_csv(of, header=is_first_part)

推荐阅读