模块化代码python时未知的librarie [英] unknown librarie when modularize code python

查看:107
本文介绍了模块化代码python时未知的librarie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试模块化我的python代码.

I try to modularize my python code .

在笔记本的主要代码中,插入以下内容:

In my main code the notebook, I insert this :

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文件:此处为代码:

And I create a module called "my_math" as an external .py file : here the code :

def feature_std_normalize(f):
    return (f - mu) / std

def feature_log_normalize(f):
   # return (f - mu) / std
    return np.log(f+1)

当我在笔记本中运行以下语句时:

When I run this statement in my notebook :

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

可以帮我解决这个问题吗?

Ca you help me to resolve this problem please?

谢谢

推荐答案

尝试在外部.py中也导入numpy,因此:

Try to import numpy also in external .py so:

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)

这篇关于模块化代码python时未知的librarie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆