我有一个从雅虎财经上拉取的股票市场数据列表,存储在pandas的DataFrame中(格式如下)。日期作为DataFrame中的索引。我想将数据(包括索引)写入SQLite数据库。
AAPL GE
Date
2009-01-02 89.95 14.76
2009-01-05 93.75 14.38
2009-01-06 92.20 14.58
2009-01-07 90.21 13.93
2009-01-08 91.88 13.95
根据我对Pandas中write_frame代码的阅读,目前不支持写入索引。我尝试使用to_records代替,但遇到Numpy 1.6.2和日期时间问题。现在我正在尝试使用.itertuples编写元组,但SQLite报错,表示不支持该数据类型(请参见下面的代码和结果)。我对Python、Pandas和Numpy相对较新,因此完全有可能我会忽略一些明显的东西。我认为我正在尝试将日期时间写入SQLite时遇到问题,但我认为我可能过于复杂化了这个问题。
我认为我可以通过升级到Numpy 1.7或Pandas的开发版本来解决此问题,该版本已在GitHub上发布了修复程序。我更喜欢使用软件的发布版本进行开发-我对此还很陌生,我不想使稳定性问题进一步混淆事情。
是否有一种方法可以使用Python 2.7.2、Pandas 0.10.0和Numpy 1.6.2来完成此操作?也许可以对日期时间进行清理?我有点超出自己的能力,任何帮助都将不胜感激。
代码:
import numpy as np
import pandas as pd
from pandas import DataFrame, Series
import sqlite3 as db
# download data from yahoo
all_data = {}
for ticker in ['AAPL', 'GE']:
all_data[ticker] = pd.io.data.get_data_yahoo(ticker, '1/1/2009','12/31/2012')
# create a data frame
price = DataFrame({tic: data['Adj Close'] for tic, data in all_data.iteritems()})
# get output ready for database export
output = price.itertuples()
data = tuple(output)
# connect to a test DB with one three-column table titled "Demo"
con = db.connect('c:/Python27/test.db')
wildcards = ','.join(['?'] * 3)
insert_sql = 'INSERT INTO Demo VALUES (%s)' % wildcards
con.executemany(insert_sql, data)
结果:
---------------------------------------------------------------------------
InterfaceError Traceback (most recent call last)
<ipython-input-15-680cc9889c56> in <module>()
----> 1 con.executemany(insert_sql, data)
InterfaceError: Error binding parameter 0 - probably unsupported type.