编程新手运行代码遇Python Pandas报错:NameError: name 'data' is not defined
NameError: name 'data' is not defined in Python/Pandas Hey there! No need to panic—this is one of the most common errors new Python/Pandas users run into, and it’s super easy to fix once you understand what’s going on. Let’s break it down step by step.
What’s causing this error?
Put simply: Python has no idea what data is. You’re trying to use a variable named data, but you never told Python what that variable actually holds, or you told it in a place it can’t see.
Common fixes based on your scenario:
1. You haven’t created or loaded the data variable yet
If you’re writing code like this and getting the error:
import pandas as pd df = pd.DataFrame(data) # Error here!
That’s because you never defined what data is. Fix it by either:
- Manually creating your data first:
import pandas as pd # Define your data as a dictionary, list of lists, etc. data = {"Product": ["Laptop", "Phone", "Tablet"], "Price": [999, 699, 299]} df = pd.DataFrame(data) - Loading data from a file:
Make sure you run the code that imports your data from a CSV/Excel/etc., and assign it todata:import pandas as pd # Load data from a CSV file (replace with your file path) data = pd.read_csv("sales_data.csv") df = pd.DataFrame(data) # Pro tip: pd.read_csv already returns a DataFrame, so you can skip assigning to data and just do df = pd.read_csv(...)
2. You misspelled the variable name
Python is case-sensitive! If you defined dataset but wrote data, or Data instead of data, Python will treat those as totally different variables. Double-check your code to make sure the name you’re using matches the name you defined.
3. data is defined outside the scope where you’re using it
If you’re using data inside a function but defined it outside, Python can’t access it by default. For example:
import pandas as pd def create_df(): df = pd.DataFrame(data) # Error! data is defined outside the function return df data = {"Name": ["Alice", "Bob"], "Age": [25, 30]} create_df()
Fix this by either:
- Passing
dataas a parameter to the function (the cleaner approach):def create_df(input_data): df = pd.DataFrame(input_data) return df data = {"Name": ["Alice", "Bob"], "Age": [25, 30]} create_df(data) - Using the
globalkeyword (only use this if necessary—global variables can get messy):def create_df(): global data # Tells Python to use the global data variable df = pd.DataFrame(data) return df
4. You forgot to run the code that defines data
If you’re using a Jupyter Notebook or a code editor with cell execution, make sure you ran the cell where you defined data before running the cell that uses it. It’s easy to skip cells accidentally!
Quick sanity check
Before using data, add a quick print(data) line. If Python throws the same error, you know you haven’t properly defined it. If it prints out your data, then the issue is somewhere else in your code.
内容的提问来源于stack exchange,提问作者Jerry Fanelli

