Background: I have a Python dataframe
Goal: I am trying to create a new string column based on values in a series of existing columns. This requires multiple 'elif' statements.
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:
UnboundLocalError: ("local variable 'result' referenced before assignment", 'occurred at index 14854')
Any help is greatly appreciated!
Aucun commentaire:
Enregistrer un commentaire