python - 模块化代码 python 时未知的库

标签 python pandas

我尝试模块化我的 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)

关于python - 模块化代码 python 时未知的库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55147462/

相关文章:

Python Find max in dataframe 列以循环查找所有值

python - 基于列的分组和取消分组

python - 如何从多个常见元素的嵌套列表创建数据框

python - 换屏事件

python - 如何有效计算 pandas 中列的线性组合?

python - 使用 flask.redirect 时 Flask 302 错误代码

python - Pandas - 以不等间隔绘制事件

python - 属性错误 : 'pywintypes.datetime' object has no attribute 'nanosecond'

python - 对数据帧字典中的每个数据帧进行排序

python - 使用 Python 的 subprocess.call 杀死 firefox 进程