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

使用Python Pandas统计各版块文章数时出现变量未定义错误求助

解决"Biology is not defined"错误并优化Pandas统计代码

问题原因

  • 你在section_articles()函数内部定义的Biology、Chemistry等变量都是局部变量,函数外部的print语句无法访问这些变量,这是报错的直接原因。
  • 函数的return()没有返回任何数据,调用函数后也未接收返回值,统计结果完全没被利用。

修正方案

方案1:调整变量作用域(不推荐)

通过global声明变量为全局变量,让外部可以访问:

def section_articles():
    global Biology, Chemistry, Computer_Science, Earth_Environment, Mathematics, Physics, Statistics
    Biology = (df2["Section"]=="Biology").sum()
    Chemistry = (df2["Section"]=="Chemistry").sum()
    Computer_Science = (df2["Section"]=="Computer Science").sum()
    Earth_Environment = (df2["Section"]=="Earth & Environment").sum()
    Mathematics = (df2["Section"]=="Mathematics").sum()
    Physics = (df2["Section"]=="Physics").sum()
    Statistics = (df2["Section"]=="Statistics").sum()

section_articles()
print("Biology", Biology)
print("Chemistry", Chemistry)
print("Computer_Science", Computer_Science)
print("Earth_Environment", Earth_Environment)
print("Mathematics", Mathematics)
print("Physics", Physics)
print("Statistics", Statistics)

注意:全局变量易引发代码维护问题,仅临时解决时使用。

方案2:封装函数返回结果(推荐)

将统计结果存入字典并返回,外部接收后打印:

def section_articles(df):
    return {
        "Biology": (df["Section"] == "Biology").sum(),
        "Chemistry": (df["Section"] == "Chemistry").sum(),
        "Computer Science": (df["Section"] == "Computer Science").sum(),
        "Earth & Environment": (df["Section"] == "Earth & Environment").sum(),
        "Mathematics": (df["Section"] == "Mathematics").sum(),
        "Physics": (df["Section"] == "Physics").sum(),
        "Statistics": (df["Section"] == "Statistics").sum()
    }

section_stats = section_articles(df2)
for section, count in section_stats.items():
    print(f"{section}: {count}")

优点:函数参数化(传入df)更灵活,返回字典便于后续处理,代码结构清晰。

方案3:使用Pandas内置方法(最优解)

直接用value_counts()一键统计所有Section的数量:

section_counts = df2["Section"].value_counts()
print(section_counts)

这是Pandas专为这类统计场景设计的方法,不仅代码简洁,还能自动处理所有存在的Section类别,无需手动枚举。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 14:35:39