python - 有没有更好的方法来提高 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 代码的性能?
(对不起我笨拙的英语,感谢您阅读所有问题)
解决方案
与其在内存中连接,不如保持输出 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)
推荐阅读
- php - 需要一个字段单独的条件验证器
- angular - 在来自数组的按钮的 ngFor 循环中生成不同的(单击)属性
- amazon-web-services - 难以理解 AWS cloudwatch 警报
- javascript - 使用 JQuery 从串联输入值的字符串中搜索并返回 JSON 文件值
- angular - 访问被 CORS 策略阻止:对预检请求的响应未通过访问控制检查
- kubernetes - Kubernetes 在使用 Helm 安装包时请求凭据
- javascript - 为什么当我触发函数时输入类型=数值为空
- html - 检查是否在 Div 区域内 onclick 事件
- swift - 使用 SwiftUI 呈现 ActionSheet 的正确方法
- c - 关于删除/替换结构