-1

I am processing a pandas dataframe df. Depending on certain conditions within df, I want to pass df (1) either to the user defined function filter() or (2) to calculate_Result().

The code for the condition is:

if df.Col1.str.contains("yes").sum() > 0:
    df = filter_df
    filter() # Loop
else:
    df = calculate_df
    calculate_result() # End 

However, I am yielding a UnboundLocalError: local variable referenced before assignment.

I keep getting this error also when I put the df = calculate_df & df = filter_df assignments in the function definitions itself:

def filter():
    df = filter_df
    ...

and

def calculate_results():
    df = calculate_df()
    ...

no matter where I put the assignments, I am yielding UnboundLocalError: local variable referenced before assignment.

How to correctly pass a local variable to a user defined function in pandas?

sudonym
  • 3,788
  • 4
  • 36
  • 61

1 Answers1

0

This isn't to do with passing a variable to a function.

You have used the name df to refer both to a global module - in df.Col1... and as the result of filter_df. That causes the error you see.

Use a different name for the local variable.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • I am not quite sure if i understand. If certain conditions in df are met, I want to rename it and continue working with it in function def1. If the conditions are not met, I want to continue working with it in function def2. Therefore, the name df has to be the same (1) when checking the condition and (2) within the function. I want to pass the same dataframe to different functions depending on a condition within the dataframe. – sudonym Dec 13 '16 at 09:24
  • No. That makes no sense, and bears no relation to the code you have posted or the problem you are having. "Renaming" a variable in one function has *absolutely nothing at all* to do with how you pass it to another function. You should post enough code so we can see what you are actually doing. – Daniel Roseman Dec 13 '16 at 09:28