You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python报错UnboundLocalError:局部变量'df'赋值前被引用,求解决方案

Fixing UnboundLocalError: local variable 'df' referenced before assignment

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 df inside a conditional branch (so it might not exist when you try to use it),
  • You’re trying to modify a global df but Python treats it as a local variable instead,
  • Or you reference df before 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:50:49