You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用pandas read_sql结合SQLAlchemy读取SQL表指定行数据

问题描述

想要通过SQLAlchemy将SQL表的部分数据读取到pandas DataFrame中,希望在读取阶段直接完成过滤(避免先读取全表再过滤造成内存浪费)。仅使用pandas时的实现方式如下:

list_of_codes_to_filter = ['code1', 'code2']
df = pd.read_csv('path/to/file')
df = df[df['code'].isin(list_of_codes_to_filter)]

尝试了以下代码但未成功实现需求:

from sqlalchemy import create_engine, select

engine = create_engine('sqlite:///path_to_db')
connection = engine.connect()
df = pd.read_sql(select().where('code'.isin(list_of_codes_to_filter)), connection)
解决方案

你的问题出在直接对字符串'code'调用isin方法——SQLAlchemy需要针对表的列对象构建过滤条件,以下是两种简单的等价实现方式:

方法1:使用SQLAlchemy Core语法(面向对象式查询)

先获取目标表的元数据,再针对列对象构建过滤逻辑:

from sqlalchemy import create_engine, select, MetaData, Table
import pandas as pd

list_of_codes_to_filter = ['code1', 'code2']

engine = create_engine('sqlite:///path_to_db')
metadata = MetaData()
# 替换为你的实际表名
target_table = Table('your_table_name', metadata, autoload_with=engine)

# 构建带过滤条件的查询语句
query = select(target_table).where(target_table.c.code.in_(list_of_codes_to_filter))

# 读取过滤后的数据到DataFrame
df = pd.read_sql(query, engine)

方法2:直接编写参数化SQL语句(直观简洁)

如果熟悉SQL语法,可直接编写带IN条件的SQL,并用参数化方式传递过滤列表(避免SQL注入风险):

import pandas as pd
from sqlalchemy import create_engine

list_of_codes_to_filter = ['code1', 'code2']

engine = create_engine('sqlite:///path_to_db')
# 替换为你的实际表名
sql_query = "SELECT * FROM your_table_name WHERE code IN :codes"

# 通过params参数传递过滤列表,自动处理SQL注入问题
df = pd.read_sql(sql_query, engine, params={"codes": list_of_codes_to_filter})

内容的提问来源于stack exchange,提问作者thosphor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 10:52:00