如何将带有索引的Pandas dataframe写入SQLite数据库

10 浏览
0 Comments

如何将带有索引的Pandas dataframe写入SQLite数据库

我有一个从Yahoo上获取的股票市场数据列表,保存在一个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
# 从Yahoo下载数据
all_data = {}
for ticker in ['AAPL', 'GE']:
    all_data[ticker] = pd.io.data.get_data_yahoo(ticker, '1/1/2009','12/31/2012')
# 创建一个数据框
price = DataFrame({tic: data['Adj Close'] for tic, data in all_data.iteritems()})
# 准备输出以便导出到数据库
output = price.itertuples()
data = tuple(output)
# 连接到一个名为"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)
 in ()
----> 1 con.executemany(insert_sql, data)
InterfaceError: Error binding parameter 0 - probably unsupported type.

0