从外部文件使用熊猫调用函数



>我将各种函数存储在一个文件中,helpers.py我在pandasnumpy之后导入。为了确保,我最后导入helpers.py文件(意思是,在调用import pandas as pdimport numpy as np等之后(

helpers.py包含包含熊猫对象(主要是数据帧(和方法的函数。

当我从笔记本中的助手调用函数(我使用 jupyter 实验室(时,例如helpers.read_FIL(...),我收到一条错误消息

"name 'pd' is not defined"

然后,我将导入语句复制到 helpers.py 文件中。 我不断收到相同的错误消息。

我真的不明白发生了什么,为什么在调用两次后仍然没有定义"pd"。是否可以将使用pandas的函数存储在单独的文件中,还是应该保留在主程序中?

代码示例:

主笔记本:

import pandas as pd
import helpers
df = helpers.read_FILUC(folder=r"G:PCNData Files 2019Balances check", file="Full_scope.txt")

helpers.py 内容:

def read_FILUC(folder, file):
" read a SAP extract file in folder and convert it into a clean dataframe"
df = pd.read_table(os.path.join(folder,file), skiprows=2,encoding='ISO-8859-1', dtype='category')
df = df.drop('Unnamed: 0', axis=1)
return df

收到的错误消息的详细信息:

NameError                              Traceback (most recent call last)
<ipython-input-2-9cddf05f0214> in <module>
----> 1 df = helpers.read_FILUC(folder=r"G:PCNData Files 2019Balances check", file="Full_scope.txt")
G:PCNProgram fileshelpers.py in read_FILUC(folder, file)
2 def read_FILUC(folder, file):
3     " read a SAP extract file in folder and convert it into a clean dataframe"
----> 4     df = pd.read_table(os.path.join(folder,file), skiprows=2,encoding='ISO-8859-1', dtype='category')
5     df = df.drop('Unnamed: 0', axis=1)
6     return df
NameError: name 'pd' is not defined

> Jupyter 不会在每次执行单元时重新加载模块。

导入语句应包含在外部.py文件中,保存,然后需要重新启动 Jupyter 内核。 然后,它考虑外部文件的修改并摆脱上述错误。

最新更新