Python报'undefined name 'sorted_by_pages''错误及代码提交咨询
Fixing the "undefined name 'sorted_by_pages'" Error
The error pops up because you’re trying to use the variable sorted_by_pages without ever defining it first. Your code reads the Excel file into df (a pandas DataFrame), but you need to explicitly create the sorted version before you can plot with it.
Here’s how to fix it:
- Add a line to sort your DataFrame by the
# num_pagescolumn and assign the result tosorted_by_pages - Then you can use that variable to generate your histogram
Modified code snippet for this part:
# You already have this line to read the Excel file df = pd.read_excel(r"C:\Users\Evelyn\Desktop\books93.xls") # Define the sorted DataFrame sorted_by_pages = df.sort_values('# num_pages') # Now plot the histogram sorted_by_pages['# num_pages'].plot(kind="hist")
Sharing Your Code & Excel File with Your Professor
Let’s break down your two questions here:
Will your professor be able to open the Excel file with your current code?
Most likely not. Right now you’re using an absolute path (C:\Users\Evelyn\Desktop\books93.xls) that points to a specific spot on your computer. Your professor’s machine won’t have this exact path, so pandas will throw a "file not found" error when they run the code.
Is packaging the code and Excel file into a zip a good idea?
Absolutely! This is actually the best practice for sharing code that relies on external files like Excel sheets. Here are a few tips to make it seamless for your professor:
- Put both your
.pycode file and thebooks93.xlsfile in the same folder - Change the file path in your code to a relative path (so it looks for the Excel file in the same folder as the code):
# Replace the absolute path with this relative path df = pd.read_excel('books93.xls') - Zip the entire folder (not just individual files) so when your professor unzips it, all files stay in the correct structure. They can just open the folder, run the code, and everything will work.
Full Corrected Code
Here’s the complete code with both fixes applied, ready to share:
import webbrowser import matplotlib.pyplot as plt import pandas as pd webbrowser.open('https://www.kaggle.com/jealousleopard/goodreadsbooks/version/6') # Use relative path for portability excel_file = 'books93.xls' df = pd.read_excel(excel_file) # Define the sorted DataFrame to fix the undefined variable error sorted_by_pages = df.sort_values('# num_pages') sorted_by_pages['# num_pages'].plot(kind="hist") print(df) plt.show()
内容的提问来源于stack exchange,提问作者Eve M

