【发布时间】:2021-01-13 02:49:50
【问题描述】:
我是韩国的一名学生,我正在使用 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 代码的性能?
(对不起,我的英语笨拙,感谢您阅读所有问题)
【问题讨论】:
-
您可以将
result_df = pd.concat(...)移出循环,方法是将所有oneday_df保存到列表中,然后执行result_df = pd.concat(list_with_oneday_dfs, axis = 0) -
进行多个连续调用并不理想。您可以改为阅读解决类似问题的这个 stackoverflow 问题:stackoverflow.com/questions/20906474/… 和这个:stackoverflow.com/questions/57000903/…
-
非常感谢!我学到了新的想法!我马上试试
标签: python pandas performance concatenation