在最近的大熊猫中,索引将保存在数据库中(您以前必须
reset_index先保存)。
遵循文档(在内存中设置SQLite连接):
import sqlite3# Create your connection.cnx = sqlite3.connect(':memory:')注意:您还可以在此处传递SQLAlchemy引擎(请参见答案结尾)。
我们可以保存
price2到
cnx:
price2.to_sql(name='price2', con=cnx)
我们可以通过
read_sql以下方式检索:
p2 = pd.read_sql('select * from price2', cnx)但是,存储(和检索)的 日期unipre
不是
Timestamp。要转换回我们开始使用的内容,可以使用
pd.to_datetime:
p2.Date = pd.to_datetime(p2.Date)p = p2.set_index('Date')我们返回与以下相同的Dataframe
prices:
In [11]: p2Out[11]: <class 'pandas.core.frame.Dataframe'>DatetimeIndex: 1006 entries, 2009-01-02 00:00:00 to 2012-12-31 00:00:00Data columns:AAPL 1006 non-null valuesGE 1006 non-null valuesdtypes: float64(2)
您还可以使用SQLAlchemy引擎:
from sqlalchemy import create_enginee = create_engine('sqlite://') # pass your db urlprice2.to_sql(name='price2', con=cnx)这使您可以使用
read_sql_table(只能与SQLAlchemy一起使用):
pd.read_sql_table(table_name='price2', con=e)# Date AAPL GE# 0 2009-01-02 89.95 14.76# 1 2009-01-05 93.75 14.38# 2 2009-01-06 92.20 14.58# 3 2009-01-07 90.21 13.93# 4 2009-01-08 91.88 13.95



