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

Python报'undefined name 'sorted_by_pages''错误及代码提交咨询

Hey there! Let's tackle your Python issues and sharing questions step by step

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:

  1. Add a line to sort your DataFrame by the # num_pages column and assign the result to sorted_by_pages
  2. 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 .py code file and the books93.xls file 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:05:23