[英]Database with Sqlite3
我正在使用Sqlite3 python库创建股价数据库。 但是我的代码要花很多时间才能运行,不知道为什么它运行缓慢。 知道如何加快速度吗? 难道我做错了什么?
我正在使用Python 3.x,Anaconda
import pandas as pd
from googlefinance.client import get_price_data, get_prices_data, get_prices_time_data
import sqlite3
db = sqlite3.connect('database.db')
c = db.cursor()
param = {'q':'MMM', 'i':"86400",'x':"NYSE",'p':"25Y"}
end_of_day = pd.DataFrame(get_price_data(param))
end_of_day['Time']=end_of_day.index
count= len(end_of_day['Time'])
c.execute('CREATE TABLE IF NOT EXISTS MMM(date,open,high,low,close,volume)')
for i in range(0,count):
c.execute('INSERT INTO MMM(date,open,high,low,close,volume) VALUES(?,?,?,?,?,?)',
(str(end_of_day.iloc[i][5]),str(end_of_day.iloc[i][0]),str(end_of_day.iloc[i][1]),
str(end_of_day.iloc[i][2]),str(end_of_day.iloc[i][3]),str(end_of_day.iloc[i][4])))
db.commit()
c.close()
db.close()
您的代码耗费时间是因为对于每个插入都使用commit并使用execute,而对于大容量插入则可以使用executemany()。
尝试将所有数据绑定到元组中,然后追加到列表中,然后将executemany用于快速批量插入:
_list=[]
for i in range(0,count):
_tuple=(str(end_of_day.iloc[i][5]),str(end_of_day.iloc[i][0]),str(end_of_day.iloc[i][1]),
str(end_of_day.iloc[i][2]),str(end_of_day.iloc[i][3]),str(end_of_day.iloc[i][4])))
_list.append(_tuple)
_tuple=()
c.executemany('INSERT INTO MMM(date,open,high,low,close,volume) VALUES(?,?,?,?,?,?)',(_list))
db.commit()
假设count
很大,那么该循环确实会使速度变慢。 您可以使用executemany()
加快处理速度。 尝试用以下方法替换循环:
params = end_of_day.apply(tuple).tolist() # Convert dataframe to list of tuples
c.executemany('INSERT INTO MMM(open,high,low,close,volume,date) VALUES(?,?,?,?,?,?)', params)
db.commit()
请参阅文档以获取有关executemany()
更多信息。
一个更简单的选择可能是简单地使用内置的Pandas函数to_sql()
:
end_of_day.to_sql('MMM', db)
在执行此操作之前,您可能必须在Pandas中重新排列一下列顺序,但这是一个非常方便的功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.