我正在尝试在Python中使一些代码更加模块化并遇到一个问题,我肯定是直截了当但我似乎无法看到问题所在。
假设我有一个脚本,比如MyScript.py:
import pandas as pd
import myFunction as mF
data_frame = mF.data_imp()
print(data_frame)
其中myFunction.py包含以下内容:
def data_imp():
return pd.read_table('myFile.txt', header = None, names = ['column'])
在命令行中运行MyScript.py会产生以下错误:
Traceback (most recent call last):
File "MyScript.py", line 5, in <module>
data_frame = mF.data_imp()
File "/Users/tomack/Documents/python/StackQpd/myFunction.py", line 2, in data_imp
return pd.read_table('myFile.txt', header = None, names = ['column'])
NameError: name 'pd' is not defined
答案 0 :(得分:3)
您需要在函数或脚本myFunction中导入pandas:
def data_imp():
import pandas as pd
return pd.read_table('myFile.txt', header = None, names = ['column'])
答案 1 :(得分:0)
这里的答案是正确的,因为您的模块确实缺少myFunction
导入。
如果陈述得更广泛,这个问题也可以包含以下内容:在循环导入的情况下,只有2种补救措施是:
import pandas as pd , but not from pandas import something