Python报错UnboundLocalError:局部变量'df'赋值前被引用,求解决方案
Hey there! That error is one of the most common gotchas when working with variables in Python functions—let’s break down exactly what’s happening and walk through the most likely fixes for your code.
What’s causing this error?
Python throws this when you try to use a local variable df in a function, but either:
- You only define
dfinside a conditional branch (so it might not exist when you try to use it), - You’re trying to modify a global
dfbut Python treats it as a local variable instead, - Or you reference
dfbefore you actually define it in the function.
Let’s go through each scenario with examples and fixes:
Scenario 1: df is only defined in conditional code
If your code looks something like this—where df gets created only if a condition is met—Python will throw the error when the condition isn’t true:
import pandas as pd def load_data(): if pd.io.common.file_exists("data.csv"): df = pd.read_csv("data.csv") # If the file doesn't exist, df was never created! print(df.shape)
Fix: Initialize df before the conditional, then check if it’s valid before using it:
import pandas as pd def load_data(): df = None # Initialize with a default value if pd.io.common.file_exists("data.csv"): df = pd.read_csv("data.csv") if df is not None: print(df.shape) else: print("No data file found!")
Scenario 2: Trying to modify a global df in a function
If you have a df defined outside your function, but you try to assign to it inside the function, Python will treat df as a local variable—even if you’re trying to use the global one first:
import pandas as pd df = pd.read_csv("global_data.csv") def clean_data(): # Python thinks df is local here, but you're trying to use it before assigning df = df.dropna()
Better fix (avoid globals when possible): Pass df as a parameter and return the modified version:
import pandas as pd def clean_data(input_df): cleaned_df = input_df.dropna() return cleaned_df df = pd.read_csv("global_data.csv") df = clean_data(df)
If you must use a global variable (not recommended for most cases), use the global keyword to tell Python you’re referring to the global df:
import pandas as pd df = pd.read_csv("global_data.csv") def clean_data(): global df # Declare df as global df = df.dropna()
Scenario 3: Referencing df before defining it in the function
Sometimes you might accidentally put the reference to df before you create it:
import pandas as pd def get_average(): print(df["value"].mean()) # Reference first df = pd.read_csv("data.csv") # Define later
Fix: Reorder your code so you define df before you use it:
import pandas as pd def get_average(): df = pd.read_csv("data.csv") print(df["value"].mean())
Quick recap
The key takeaway is to make sure df is properly defined in the scope where you’re using it:
- Always initialize variables before conditional branches if you plan to use them outside the branch,
- Avoid relying on global variables—pass data as function parameters instead,
- Double-check the order of your code: define first, use second.
内容的提问来源于stack exchange,提问作者J.Doe

