如何用Pandas读取CSV文件?解决forestfire_df未定义报错
问题解决方法
你的代码有两个关键问题导致报错:
- 未导入
os模块,但代码中使用了os.path.exists()和os.getcwd()方法,会先触发模块未找到的错误 - 变量
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
相关产品推荐
相关产品推荐

