【问题标题】:Importing functions into Jupyter Notebook getting a name error将函数导入 Jupyter Notebook 时出现名称错误
【发布时间】:2021-03-17 15:02:03
【问题描述】:

我正在 AWS Sagemaker 实例上使用 Jupyter 笔记本。为方便起见,我编写了一个 .py 文件,其中定义了几个函数;

#function to gather the percent of acts in each label feature combo

def compute_pct_accts(data, label_cnt):
"""
data is the output from aggregate_count
labe_cnt gives the breakdown of data for each target value
"""

label_data_combined = pd.merge(data, label_cnt, how='inner', left_on= 'label', right_on = 'label')
label_data_combined['Act_percent'] = np.round((label_data_combined['ACT_CNT']/label_data_combined['Total_Cnt'])*100,2)
return label_data_combined


#write a function to perform aggregation for target and feature column

def aggregate_count(df, var, target):

"""
df is the dataframe,
var is the feature name
target is the label varaible(0 or 1)
"""

label_var_cnt = df.groupby([var,target],observed=True)['ID'].count()
label_var_cnt = label_var_cnt.reset_index()
label_var_cnt.rename(columns={'ID':'ACT_CNT'},inplace=True)
return label_var_cnt

这两个函数都存储在一个名为 file1.py 的 .py 文件中。然后在我输入的笔记本中检索它们;

from file1 import *
import pandas as pd

这个命令确实导入了这两个函数。但是当我尝试运行该函数时;

compute_pct_accts(GIACT_Match_label_cnt, label_cnt)

我收到名称错误;


pd not found

请注意,我已在我的 jupyter 笔记本中将 pandas 作为 pd 导入。我知道使用该选项

%run -i compute_pct_accts_new.py

但这迫使我用该函数编写一个新的 python 文件。我的问题是,我们能否拥有一个包含所有函数的 python 文件,以便我们可以一次导入所有函数并在 notebook 中交互使用。 感谢您的帮助。

【问题讨论】:

  • 不,您还需要在您的file1.py 中导入pandas

标签: python pandas jupyter-notebook


【解决方案1】:

尝试在包含您要导入的函数的 .py 文件中导入 pandas。

【讨论】:

  • 感谢您的回复。我确实按照建议在 python 文件中添加了import pandas as pd。但是错误还是一样name pd is not defined.
  • 查看这篇文章:hhttps://stackoverflow.com/a/54725559 也许您可以创建一个包含您需要的功能的模块并将其安装在您的环境中。然后你会从所述模块导入它们
猜你喜欢
  • 1970-01-01
  • 2021-12-10
  • 1970-01-01
  • 2019-06-11
  • 2021-07-04
  • 2019-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多