在函数内部定义全局时出现 UnboundLocalError

我知道这是一个非常常见的错误,但我可以找到我的错误。我有带有周边数据的数据框,例如:


>>>name    perimeter

0  al      24.5

1  dl      43.7

2  yl      1222.4

3  pl      213.2

4  kl      120

...

我想检查周长中位数是多少,然后根据周长中位数添加新列。我在函数之前定义中位数,然后在函数内将中位数定义为全局:


per_median=df['perimeter'].median()


def z(row):

    global per_median

    if row['perimeter'] > per_median:

        val = 'yes'

    elif row['perimeter'] < per_median:

        val = 'no'

    return val


df['perimeter_warning'] = df.apply(z,axis=1)


由于某种原因,即使我在函数内使用全局,我仍然收到此错误:


UnboundLocalError:赋值前引用的局部变量“val”


我做错了什么?我预计将其定义为全局将解决问题。


慕神8447489
浏览 108回答 2
2回答

临摹微笑

尝试在代码中添加另一种场景,其中if row['perimeter'] == per_median: 然后为 val 设置一些值。或者,如果您不想处理此问题,请在使用之前尝试为 val 分配默认值。

万千封印

缺少处理row['perimeter']等于的情况,因此未设置变量。per_medianval编辑代码来处理这种情况:import pandas as pdimport numpy as npdf = pd.DataFrame({'name':['al', 'dl', 'yl', 'pl', 'kl'],'perimeter':[24.5, 43.7, 1222.4, 213.2, 120]})per_median=df['perimeter'].median()def z(row):&nbsp; &nbsp; global per_median&nbsp; &nbsp; if row['perimeter'] > per_median:&nbsp; &nbsp; &nbsp; &nbsp; val = 'yes'&nbsp; &nbsp; elif row['perimeter'] < per_median:&nbsp; &nbsp; &nbsp; &nbsp; val = 'no'&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; val = 'equals'&nbsp; &nbsp; return valdf['perimeter_warning'] = df.apply(z,axis=1)print(df)输出:&nbsp; name&nbsp; perimeter perimeter_warning0&nbsp; &nbsp;al&nbsp; &nbsp; &nbsp; &nbsp;24.5&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; no1&nbsp; &nbsp;dl&nbsp; &nbsp; &nbsp; &nbsp;43.7&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; no2&nbsp; &nbsp;yl&nbsp; &nbsp; &nbsp;1222.4&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;yes3&nbsp; &nbsp;pl&nbsp; &nbsp; &nbsp; 213.2&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;yes4&nbsp; &nbsp;kl&nbsp; &nbsp; &nbsp; 120.0&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; equals
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python