【发布时间】:2022-02-24 17:26:45
【问题描述】:
我有一个从雅虎提取的股票市场数据列表,包含在 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 代码的阅读,它是does not currently support writing the index。我尝试改用 to_records,但遇到了issue with Numpy 1.6.2 and datetimes。现在我正在尝试使用 .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.
【问题讨论】:
-
如果你只想把索引作为表中的一列,你就不能给你的DataFrame一个重复索引的列吗?