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

Python多循环执行SQL查询并按类保存至不同DataFrame

实现按班级拆分的参数化SQL查询与DataFrame存储

需求说明

针对每个班级(1-4),批量执行基于inputs参数范围的SQL查询,最终将每个班级的所有查询结果合并为独立的DataFrame(如df_class1、df_class2等)。

完整实现代码

import pandas as pd

# 定义SQL模板(占位符顺序:班级编号、student_number下限、student_number下限)
query_template = '''
select name 
from my_table
where class = {}
and student_number > {}
and student_number <= {} + 10
group by name
'''

inputs = list(range(0, 100, 10))
classes = [1, 2, 3, 4]

# 用字典统一管理各班级的DataFrame
class_dataframes = {}

for class_num in classes:
    # 初始化当前班级的空DataFrame
    current_class_df = pd.DataFrame()
    for num in inputs:
        # 替换SQL模板中的参数,生成可执行的查询语句
        sql = query_template.format(class_num, num, num)
        # 执行查询并转换为DataFrame
        query_result = my_db.execute(sql)
        temp_df = pd.DataFrame(query_result)
        # 合并当前批次的结果到班级DataFrame
        current_class_df = pd.concat([current_class_df, temp_df], ignore_index=True)
    # 将班级结果存入字典,键为目标变量名
    class_dataframes[f'df_class{class_num}'] = current_class_df

# 可选:将字典中的DataFrame转为全局变量,直接通过df_class1、df_class2访问
for df_name, df in class_dataframes.items():
    globals()[df_name] = df

关键细节说明

  • 参数匹配:确保format方法的参数顺序和SQL模板中的占位符完全对应,避免查询逻辑错误
  • 结果管理:用字典存储各班级结果,比手动创建多个变量更灵活,班级数量变动时无需修改大量代码
  • 合并方式:使用pd.concat替代已弃用的append方法,符合pandas最新语法规范,执行效率更高
  • 独立变量生成:通过globals()可以直接将字典中的DataFrame转为df_class1这类全局变量,满足直接调用的需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 03:24:37