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

如何用Pandas读取CSV文件?解决forestfire_df未定义报错

问题解决方法

你的代码有两个关键问题导致报错:

  1. 未导入os模块,但代码中使用了os.path.exists()和os.getcwd()方法,会先触发模块未找到的错误
  2. 变量forestfire_df从未被定义:你仅标注了# TODO 1.1,但没有执行赋值操作将CSV数据存入该变量,直接调用时解释器自然会提示变量未定义。

修正后的完整代码如下:

import numpy as np
import pandas as pd
import os  # 补充导入os模块

if not os.path.exists("forestfires.csv"):
    raise Exception(f"The forestfires.csv is not detected in your local path! " \
                    f"You need to move the 'forestfires.csv' file to the same " \
                    f"location/directory as this notebook which is {os.getcwd()}")     
# 完成TODO:将读取的CSV数据存入变量
forestfire_df = pd.read_csv("forestfires.csv")

display(forestfire_df)

display(pd.read_csv("forestfires.csv"))

([
    (np.all(forestfire_df.iloc[0].values == np.array([7, 5, 'mar', 'fri', 86.2, 26.2, 94.3, 5.1, 8.2, 51, 6.7, 0.0, 0.0],
      dtype=object)), '')
])

关键修正点

  • 添加import os语句,解决os模块依赖问题
  • 在# TODO 1.1位置补充forestfire_df = pd.read_csv("forestfires.csv"),完成变量的定义与赋值,之后调用该变量就不会报错了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 15:00:45