Jar*_*red 92 python sqlalchemy pandas flask-sqlalchemy
这个主题暂时没有在这里或其他地方得到解决.有没有将SQLAlchemy <Query object>转换为pandas DataFrame 的解决方案?
Pandas有能力使用,pandas.read_sql但这需要使用原始SQL.我有两个理由想要避免它:1)我已经拥有使用ORM的一切(这本身就是一个很好的理由)和2)我使用python列表作为查询的一部分(例如:我的模型类.db.session.query(Item).filter(Item.symbol.in_(add_symbols)在哪里Item并且add_symbols是一个列表).这相当于SQL SELECT ... from ... WHERE ... IN.
有可能吗?
van*_*van 164
以下应该适用于大多数情况:
df = pd.read_sql(query.statement, query.session.bind)
有关pandas.read_sql参数的更多信息,请参阅文档.
Cha*_*hit 65
为了让新手大熊猫程序员更清楚,这里有一个具体的例子,
pd.read_sql(session.query(Complaint).filter(Complaint.id == 2).statement,session.bind) 
在这里,我们从投诉表(sqlalchemy model is Complaint)中选择一个id = 2的投诉
taf*_*fit 11
为了完整起见:作为 Pandas-function 的替代方案read_sql_query(),您还可以使用 Pandas-DataFrame-functionfrom_records()将structured or record ndarray to DataFrame. 
如果您已经在 SQLAlchemy 中执行了查询并且结果已经可用,这会派上用场:
import pandas as pd 
from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker
SQLALCHEMY_DATABASE_URI = 'postgresql://postgres:postgres@localhost:5432/my_database'
engine = create_engine(SQLALCHEMY_DATABASE_URI, pool_pre_ping=True, echo=False)
db = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))
Base = declarative_base(bind=engine)
class Currency(Base):
    """The `Currency`-table"""
    __tablename__ = "currency"
    __table_args__ = {"schema": "data"}
    id = Column(Integer, primary_key=True, nullable=False)
    name = Column(String(64), nullable=False)
# Defining the SQLAlchemy-query
currency_query = db.query(Currency).with_entities(Currency.id, Currency.name)
# Getting all the entries via SQLAlchemy
currencies = currency_query.all()
# We provide also the (alternate) column names and set the index here,
# renaming the column `id` to `currency__id`
df_from_records = pd.DataFrame.from_records(currencies
    , index='currency__id'
    , columns=['currency__id', 'name'])
print(df_from_records.head(5))
# Or getting the entries via Pandas instead of SQLAlchemy using the
# aforementioned function `read_sql_query()`. We can set the index-columns here as well
df_from_query = pd.read_sql_query(currency_query.statement, db.bind, index_col='id')
# Renaming the index-column(s) from `id` to `currency__id` needs another statement
df_from_query.index.rename(name='currency__id', inplace=True)
print(df_from_query.head(5))
所选解决方案对我不起作用,因为我不断收到错误消息
AttributeError:'AnnotatedSelect'对象没有属性'lower'
我发现以下工作:
df = pd.read_sql_query(query.statement, engine)
如果您想编译带有参数和方言特定参数的查询,请使用如下内容:
c = query.statement.compile(query.session.bind)
df = pandas.read_sql(c.string, query.session.bind, params=c.params)
小智 5
from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
engine = create_engine('postgresql://postgres:postgres@localhost:5432/DB', echo=False)
Base = declarative_base(bind=engine)
Session = sessionmaker(bind=engine)
session = Session()
conn = session.bind
class DailyTrendsTable(Base):
    __tablename__ = 'trends'
    __table_args__ = ({"schema": 'mf_analysis'})
    company_code = Column(DOUBLE_PRECISION, primary_key=True)
    rt_bullish_trending = Column(Integer)
    rt_bearish_trending = Column(Integer)
    rt_bullish_non_trending = Column(Integer)
    rt_bearish_non_trending = Column(Integer)
    gen_date = Column(Date, primary_key=True)
df_query = select([DailyTrendsTable])
df_data = pd.read_sql(rt_daily_query, con = conn)
| 归档时间: | 
 | 
| 查看次数: | 42969 次 | 
| 最近记录: |