繁体   English   中英

如何从 Python 中的另一个文件调用 function 中定义的变量?

[英]How can I call a variable defined inside a function from another file in Python?

我有以下名为calculo_indice.py的文件

import pandas as pd

def limites(df,n):
    n_sigma = n * df.valor_unitario.std()
    mean = df.valor_unitario.mean()
    lower_bound: float = mean - n_sigma
    upper_bound: float = mean + n_sigma
    return (lower_bound,upper_bound)


def indice(df):
    df['isOutlier'] = df['valor_unitario'].apply(lambda x: True if x < lower_bound or x > upper_bound else False)
    df = df[~df.isOutlier]
    df['indice'] = df['valor_unitario'].apply(lambda x: ((x-lower_bound)/(upper_bound-lower_bound))*2000)
    df = df.astype({'indice': 'int64'})

它旨在计算 dataframe 列的下限和上限(第一个 function 称为limites )然后计算这些边界上的索引(函数称为indice

运行calculo_indice.py文件一切正常,但是在运行调用这些函数的原始文件时,我得到一个NameError

我将该文件作为import calculo_indice as indice ,然后像这样调用这些函数:

indice.limites(df, 2)

indice.indice(df)

我也尝试print(lower_bound)这就是我尝试返回的原因

Traceback (most recent call last):
  File "C:\Users\...\Indice.py", line 19, in <module>
    indice.indice(df)
  File "C:\Users\...\calculo_indice.py", line 12, in indice
    df['isOutlier'] = df['valor_unitario'].apply(lambda x: True if x < lower_bound or x > upper_bound else False)
  File "C:\ProgramData\Anaconda3\envs\Indice\lib\site-packages\pandas\core\series.py", line 4138, in apply
    mapped = lib.map_infer(values, f, convert=convert_dtype)
  File "pandas\_libs\lib.pyx", line 2467, in pandas._libs.lib.map_infer
  File "C:\Users\...\calculo_indice.py", line 12, in <lambda>
    df['isOutlier'] = df['valor_unitario'].apply(lambda x: True if x < lower_bound or x > upper_bound else False)
NameError: name 'lower_bound' is not defined

Process finished with exit code 1

我究竟做错了什么? 感谢您的帮助

lower_boundupper_bound仅在您的限制limites本地 scope中定义。 如果它们也需要在索引中定义,那么您必须将它们作为参数传递,这样它们就在indice中:

我还修改了您的indice 首先,您需要返回 DataFrame,这样您就可以将您的更改分配给一个变量并让它们真正生效。 其次,您的大多数Series.apply调用效率低下,并且存在将作用于整个 Series 的矢量化替代方案。

calculo_indice.py

def limites(df,n):
    n_sigma = n * df.valor_unitario.std()
    mean = df.valor_unitario.mean()
    lower_bound: float = mean - n_sigma
    upper_bound: float = mean + n_sigma
    return (lower_bound, upper_bound)


def indice(df, lower_bound, upper_bound):
    # Vectorized check
    df['isOutlier'] = ~df['valor_unitario'].between(lower_bound, upper_bound)
    df = df[~df.isOutlier]
    
    # Vectorized calculation
    df['indice'] = (df['valor_unitario']-lower_bound)/(upper_bound-lower_bound)*2000
    df = df.astype({'indice': 'int64'})
    
    return df

然后,您将调用limites ,将返回值定义给某些变量(因为它返回下限和上限)并将这些变量传递给indice

import calculo_indice as indice

# Assign lower bound and upper bound to variables `lb` and `ub` respectively
lb,ub = indice.limites(df, 2)

df = indice.indice(df, lower_bound=lb, upper_bound=ub)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM