def df_query(self, query, with_labels=False):
"""
Run a :mod:`sqlalchemy` query and return result as a :class:`pandas.DataFrame`
Args:
query (sqlalchemy.orm.query.Query): query object, usually generated by :func:`session.query()` in
an :class:`sqlalchemy.orm.session.Session`
with_labels (bool): A query for fields with the same name from different tables will cause problems
when converting it to a :class:`pandas.DataFrame`, because there will be duplicate column names.
When setting `with_labels=True`, disambiguation labels are assigned to all (!)
fields in the query - the field name is prefixed with the column name. This enables
querying fields with identical names from multiple tables but getting unique column names in the output.
:return: query result as :class:`pandas.DataFrame`
"""
import pandas as pd
if with_labels:
query = query.with_labels()
# compile sql statement, including arguments
statement = query.statement.compile(self.engine)
# run query
return pd.read_sql_query(sql=statement, con=self.engine)
评论列表
文章目录