Mohammad Amir
Mohammad Amir

Reputation: 133

UnboundLocalError: Why this code is giving unboundeLocalError?

Why this code is giving error - UnboundLocalError: local variable 'tab' referenced before assignment

Here is my code -

def univar_tables(col_name):
    if col_name in cat_cols:
        tab = pd.DataFrame(pd.crosstab(df[col_name], columns = "count"))
        tab["Row %"] = tab["count"]/len(df)
    elif col_name in num_cols:
        df["binned"] = pd.qcut(df[col_name], q=10, duplicates ='drop', precision = 2)
        tab = pd.DataFrame(pd.crosstab(df["binned"], columns = "count"))
        tab["Row %"] = tab["count"]/len(df)
    return tab

Upvotes: 0

Views: 26

Answers (2)

Valdi_Bo
Valdi_Bo

Reputation: 31011

Your function (univar_tables) has actually 3 paths of execution:

  • col_name in cat_cols,
  • col_name in num_cols,
  • otherwise (neither the first nor the second condition met).

In first 2 cases tab variable is first set and then referenced.

But in the third case tab has not been set and it is only referenced in return instruction.

This is probably the actual cause of your error. Maybe in this (third) case you should set tab to some value.

Upvotes: 0

Krishna Chaurasia
Krishna Chaurasia

Reputation: 9590

You are getting the error since the tab object is created conditionally and it might be possible that both the conditions might fail to satisfy for some input date. You can avoid the error by creating the tab object with some defaults None.

def univar_tables(col_name):
    tab = None
    if col_name in cat_cols:
        tab = pd.DataFrame(pd.crosstab(df[col_name], columns = "count"))
        tab["Row %"] = tab["count"]/len(df)
    elif col_name in num_cols:
        df["binned"] = pd.qcut(df[col_name], q=10, duplicates ='drop', precision = 2)
        tab = pd.DataFrame(pd.crosstab(df["binned"], columns = "count"))
        tab["Row %"] = tab["count"]/len(df)
    return tab

Upvotes: 1

Related Questions