I'm having a strange scope problem. The following code is a cell in a Jupyter Notebook. I have assigned p1_total_value
and p2_total_value
within correlation_check()
. Then, later in correlation_check()
, project_value(row)
is defined and then finally applied to a DataFrame.
When I run this code, I get an UnboundLocalError saying that p1_total_value
was referenced before assigment. If I add Global p1_total_value
to project_value(row)
, it tells me that p1_total_value
is undefined. It seems like somehow the pandas.apply() is happening before the code that precedes it in correlation_check()
.
# Check for correlation between the values deteremined in this analysis and the final scores of
# the games from in_depth_games
def correlation_check(game):
player_count = game.Player.max()
game_len = (max([int(row) for row in game.Generation if row not in ['Last', 'Final']]))
calculated_values = all_gens_full_db(player_count)
if player_count == 2:
compression = 13/game_len
elif player_count == 3:
compression = 11/game_len
elif player_count in [4, 5]:
compression = 10/game_len
p1_total_value = 0
p2_total_value = 0
p1_final_score = game.iloc[-2].Action
p2_final_score = game.iloc[-1].Action
def project_value(row):
if 'played' in row.Action:
project_name = row.Action.split('played ')[1]
gen = round(compression * int(row.Generation))
project_row = calculated_values[calculated_values.Title == project_name]
value = int(project_row[f'Value Gen{gen}'])
if int(row.Player) == 1:
p1_total_value += value
else: p2_total_value += value
game = game.apply(project_value, axis=1)
#print(f'''
# Player 1 total project value: {p1_total_value}
# Player 2 total project value: {p2_total_value}
# \n
# Player 1 final score: {}''')
correlation_check(in_depth_game_1)