我需要使用Python中的odo库从MySQL数据库获取数据到Pandas dataframe中。Odo的文档只提供了传递表名以获取数据的信息,但是如何传递从数据库获取所需数据的SQL查询字符串呢?
下面的代码可以工作:
导入odo
将熊猫作为pd导入
data = odo('mysql+pymysql://username:{0}@localhost/dbname::{1}'.format('password','table_name'),pd.DataFrame)
但是如何传递SQL字符串而不是表名呢?因为我需要连接多个其他表来提取所需的数据。
发布于 2017-10-13 08:53:19
模块不支持将字符串直接传递给odo。使用列出的工具有三种移动数据的方法。
首先,创建一个字符串形式的sql查询,并使用以下命令读取:
data = pandas.read_sql_query(sql, con, index_col=None,
coerce_float=True, params=None,
parse_dates=None, chunksize=None)[source]参考http://pandas.pydata.org/pandas-docs/version/0.20/generated/pandas.read_sql_query.html#pandas.read_sql_query
其次,利用odo方法需要在字典中运行查询,然后在odo(源,目标)结构中使用字典。
cursor.execute(sql)
results = db.engine.execute(sql)
data = odo(results, pd.DataFrame)https://media.readthedocs.org/pdf/odo/latest/odo.pdf的ref pg 30
参考How to execute raw SQL in SQLAlchemy-flask app
参考cursor.fetchall() vs list(cursor) in Python
最后,为了提高执行速度,请考虑为结果中的每个结果附加pandas数据帧。
result = db.engine.execute(sql).fetchone()
data = pd.DataFrame(index=index, columns=list('AB'))
data = df_.fillna(0) # with 0s rather than NaNs
while result is not None:
dataappend = pd.DataFrame(result, columns=list('AB'))
data.append(dataappend)
result = db.engine.execute(sql).fetchone()参考https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.append.html
https://stackoverflow.com/questions/46718093
复制相似问题