简体   繁体   English

带有日期索引的熊猫数据框->插入MySQL

[英]pandas dataframe with Date index -> insert into MySQL

The object df is of type pandas.core.frame.DataFrame. 对象df的类型为pandas.core.frame.DataFrame。

In [1]: type(df)
Out[1]: pandas.core.frame.DataFrame

The index of df is a DatetimeIndex df的索引是DatetimeIndex

In [2]: type(df.index)
Out[2]: pandas.tseries.index.DatetimeIndex

And con gives a working MySQLdb connection 并且con提供了一个有效的MySQLdb连接

In [3]: type(con)
Out[3]: MySQLdb.connections.Connection

I've not been able to get this dataframe entered into a MySQL database correctly, specifically, the date field comes through as null when using the following (as well as some variations on this). 我无法正确地将此数据帧输入到MySQL数据库中,特别是,在使用以下内容(以及对此的某些变化)时,日期字段变为null。

df.to_sql( name='existing_table',con=con, if_exists='append', index=True, index_label='date', flavor='mysql', dtype={'date': datetime.date})

What are the steps required to have this dataframe entered correctly into a local MySQL database, with 'date' as a date field in the db? 要将此数据帧正确输入到本地MySQL数据库(以db中的“ date”作为日期字段),需要执行哪些步骤?

To correctly write datetime data to SQL, you need at least pandas 0.15.0. 要将日期时间数据正确写入SQL,您至少需要熊猫0.15.0。

Starting from pandas 0.14, the sql functions are implemented using SQLAlchemy to deal with the database flavor specific differences. 从pandas 0.14开始,使用SQLAlchemy实施sql函数,以处理数据库风味特定的差异。 So to use to_sql , you need to provide it an SQLAlchemy engine instead of a plain MySQLdb connection: 因此,要使用to_sql ,您需要为其提供一个SQLAlchemy引擎,而不是简单的MySQLdb连接:

from sqlalchemy import create_engine
engine = create_engine('mysql+mysqldb://....')

df.to_sql('existing_table', engine, if_exists='append', index=True, index_label='date')

Note: you don't need to provide the flavor keyword anymore. 注意:您不再需要提供flavor关键字。

Plain DBAPI connections are no longer supported for writing data to SQL, except for sqlite. 除sqlite之外,不再支持将纯DBAPI连接用于将数据写入SQL。

See http://pandas.pydata.org/pandas-docs/stable/io.html#io-sql for more details. 有关更多详细信息,请参见http://pandas.pydata.org/pandas-docs/stable/io.html#io-sql

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM