【发布时间】: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