UnboundLocalError:在Pandas中分配之前引用了局部变量“ y”

时间:2019-08-30 17:02:21

标签: python pandas function if-statement apply

我正在尝试将一种功能应用于一列,但出现错误

Journal

我的代码在下面

Name    weight
Person1 30
Person2 70

def classify(x): if 0 <= x < 20: y = "0 to 20%" if 20 < x < 40: y = "20 to 40%" if 40 < x < 60: y = "40 to 60%" if 60 < x < 80: y = "60 to 80%" if 80 < x <= 100: y = "80 to 100%" return ( y) 抛出本地限制错误

如果我使用print而不是return,我可以看到输出

预期

df['Target'] = df['weight'].apply(lambda x: classify(x))

1 个答案:

答案 0 :(得分:2)

为什么不使用cut

df['Target']=pd.cut(df['weight'],[0,20,40,60,80,100])