如何用Pandas根据当日日期提取Excel课程表对应行数据
Hey there! Let's get that daily schedule filtering working properly. The key issue here is making sure the date formats in your DataFrame match the date.today() output, so Pandas can correctly compare them. Here's a step-by-step solution:
1. Ensure Your Date Column is in the Right Format
First, double-check that your DATE column is converted to a date-only type (not datetime with time, or a string). If you haven't already done this correctly, add this line after reading your Excel file:
import pandas as pd from datetime import date # Read the Excel file (you probably have this already) df = pd.read_excel("your_schedule.xlsx", parse_dates=["DATE"]) # Convert DATE column to date-only type to match date.today() df["DATE"] = df["DATE"].dt.date
2. Filter for Today's Schedule
Now, grab today's date and filter the DataFrame. We'll also add a check in case there are no classes scheduled for today:
# Get today's date today_date = date.today() # Filter the dataframe for rows where DATE matches today today_classes = df[df["DATE"] == today_date] # Print the result neatly if not today_classes.empty: print("Today's Classes:\n") print(today_classes.to_string(index=False)) # Hides the index for cleaner output else: print("No classes scheduled for today! 🎉")
Common Mistakes to Avoid
- Mismatched Data Types: If your
DATEcolumn is stored as a string (e.g., "2024-05-20") instead of adateobject, the comparisondf["DATE"] == today_datewill fail. Always convert date columns to proper date/datetime types first. - Datetime with Time: If your
DATEcolumn includes time values (like2024-05-20 00:00:00), usedf["DATE"].dt.dateto extract just the date part before comparing.
This should give you the single row (or rows, if multiple entries exist for the same date) of today's courses, formatted cleanly.
内容的提问来源于stack exchange,提问作者user3137708

