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

调用含if-else分支的自定义函数返回DataFrame后Jupyter提示df未定义

报错原因

你定义的server函数会返回DataFrame对象,但你在Jupyter中调用时没有将返回结果赋值给变量,函数内部定义的df是局部作用域变量,仅在函数运行过程中有效,不会自动保存到Jupyter的全局命名空间,因此后续直接调用df会提示变量未定义。

解决方法

修改Jupyter中的调用代码,将函数返回结果赋值给变量df即可:

import custom_functions as cf
df = cf.server("local","local_db","vw_local")

完成赋值后就可以正常执行df.head()等pandas操作。

原有代码优化建议

你目前的自定义函数存在冗余和潜在问题,可调整为如下写法:

  • 依赖库导入统一放在文件顶部,无需每个条件分支重复导入
  • 修正else分支缩进错误,补充异常分支的返回逻辑
  • 你原代码中云服务器的数据库连接地址仍写为localhost,记得修改为实际的云数据库访问地址
# custom_functions.py 优化后代码
import pandas as pd
from sqlalchemy import create_engine
import pymysql

def server(server_name, database_name, view_name):
    if server_name == "local":
        print('Connecting to the LOCAL database...')
        db_connection_str = 'mysql+pymysql://username:password@localhost/' + database_name
    elif server_name == "cloud":
        print('Connecting to the CLOUD database...')
        # 替换为云数据库实际访问地址
        db_connection_str = 'mysql+pymysql://username:password@你的云数据库地址/' + database_name
    else:
        print("不支持的服务器类型,请输入local或cloud")
        return None
    db_connection = create_engine(db_connection_str)
    df = pd.read_sql('SELECT * FROM ' + view_name, con=db_connection, parse_dates=['encounter_date'])
    return df

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 11:06:04