【问题标题】:Calling functions using pandas from an external file使用 pandas 从外部文件调用函数
【发布时间】:2020-06-22 22:35:41
【问题描述】:

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

helpers.py 包含包含 pandas 对象(主要是 DataFrames)和方法的函数。

当我从笔记本中的助手调用函数时(我使用 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:\PCN\Data Files 2019\Balances 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:\PCN\Data Files 2019\Balances check", file="Full_scope.txt")

G:\PCN\Program files\helpers.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

【问题讨论】:

标签: python pandas import


【解决方案1】:

每次执行单元格时,Jupyter 都不会重新加载模块。

导入语句应包含在外部 .py 文件中,保存,然后需要重新启动 Jupyter 内核。 然后,它考虑到外部文件的修改,消除了上面提到的错误。

【讨论】:

    猜你喜欢
    • 2019-02-10
    • 1970-01-01
    • 2017-12-02
    • 2011-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多