[英]Python: Use Function to Create New String Column in Dataframe Using Multiple Elif Statements
Background: I have a Python dataframe 背景:我有一个Python数据框
Goal: I am trying to create a new string column based on values in a series of existing columns. 目标:我试图根据一系列现有列中的值创建一个新的字符串列。 This requires multiple 'elif' statements. 这需要多个“ elif”语句。
Below is my (sample) code which is erroring out: 下面是我的(示例)代码,该代码有误:
def rationale(row):
if row['Recommendation No. 1'] == 'Category_A':
result = []
result.append(row['First_Flag'])
result.append(row['Second_Flag'])
result.append(row['Third_Flag'])
result = ' '.join(result)
return result
elif row['Recommendation No. 1'] == 'Category_B':
result.append(row['Fourth_Flag'])
result.append(row['Fifth_Flag'])
result.append(row['Sixth_Flag'])
result.append(row['Seventh_Flag'])
result = ' '.join(result)
return result
elif row['Recommendation No. 1'] == 'Category_C':
result.append(row['Eigth_Flag'])
result.append(row['Ninth_Flag'])
result.append(row['Tenth_Flag'])
result.append(row['Eleventh_Flag'])
result = ' '.join(result)
return result
else:
return np.nan
df_top3_rationale['Recommendation No. 1 Rationale'] = df_top3_rationale.apply(rationale, axis=1)
This is the error I get on the 'elif' statements: 这是我在'elif'语句上得到的错误:
UnboundLocalError: ("local variable 'result' referenced before assignment", 'occurred at index 14854')
Any help is greatly appreciated! 任何帮助是极大的赞赏!
The problem is that you define result
only inside the first if
block, so if the elif
statements execute, they do not have access to a variable named result
, which is why the error says that the variable result
is referenced before assignment (assignment is in this line: result = []
). 问题在于您只能在第一个if
块内定义result
,因此,如果执行elif
语句,它们将无法访问名为result
的变量,这就是为什么错误指出变量result
在赋值之前被引用(赋值在这行: result = []
)。 What you should do is either put the line result = []
before the conditionals, or include it in every if
and elif
block. 您应该做的是将result = []
行result = []
放在条件elif
之前,或者将其包括在每个if
和elif
块中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.