python - 模块化代码python时的未知库
问题描述
我尝试模块化我的 python 代码。
在我的笔记本主代码中,我插入了这个:
import numpy as np
import pandas as pd
from pandas import DataFrame
import my_math
df["std_line_amount_log_normal"] = df["std_line_amount"].apply(lambda f: my_math.feature_log_normalize(f))
我创建了一个名为“my_math”的模块作为外部 .py 文件:这里的代码:
def feature_std_normalize(f):
return (f - mu) / std
def feature_log_normalize(f):
# return (f - mu) / std
return np.log(f+1)
当我在笔记本中运行此语句时:
df["std_line_amount_log_normal"] = df["std_line_amount"].apply(lambda f: my_math.feature_log_normalize(f))
我收到此错误:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-90-32256b03bfa2> in <module>()
----> 1 df["std_line_amount_log_normal"] = df["std_line_amount"].apply(lambda f: my_math.feature_log_normalize(f))
~/anaconda3/envs/python3/lib/python3.6/site-packages/pandas/core/series.py in apply(self, func, convert_dtype, args, **kwds)
2549 else:
2550 values = self.asobject
-> 2551 mapped = lib.map_infer(values, f, convert=convert_dtype)
2552
2553 if len(mapped) and isinstance(mapped[0], Series):
pandas/_libs/src/inference.pyx in pandas._libs.lib.map_infer()
<ipython-input-90-32256b03bfa2> in <lambda>(f)
----> 1 df["std_line_amount_log_normal"] = df["std_line_amount"].apply(lambda f: my_math.feature_log_normalize(f))
~/SageMaker/my_math.py in feature_log_normalize(f)
10
11 def feature_log_normalize(f):
---> 12 # return (f - mu) / std
13 return np.log(f+1)
14
NameError: name 'np' is not defined
你能帮我解决这个问题吗?
谢谢你
解决方案
尝试在外部 .py 中导入 numpy,这样:
import numpy as np
def feature_std_normalize(f):
return (f - mu) / std
def feature_log_normalize(f):
# return (f - mu) / std
return np.log(f+1)
推荐阅读
- kubernetes - 注入 istio envoy 后的 Hazelcast 问题
- javascript - Vue 2 的 Vue 3 传送
- c# - 当用户在表 1 中创建时,将用户名和 id 复制到表 2
- php - 我的代码是否足以防止 SQL 注入?
- r - autostsm stsm_estimate 错误:exo 必须是数据框或数据表
- android-studio - 创建新的密钥库 Android Studio
- java - 如何在 Java 中同步两个线程
- go - Buffo 写入 net.Conn 永久阻塞
- python - 使用python从url抓取和下载excel文件
- amazon-web-services - 为什么 terraform plan 或 terraform apply 使用与应使用不同的工作空间?