Python新手求助:如何通过用户输入过滤DataFrame(含共享单车代码)
Hey there! Let's break this down step by step since you're just getting started with Python and this bikeshare project—totally get how applying new concepts can feel tricky when you're working on a real project. Your start with the get_filters() function is great, let's finish it up and then connect it to filtering the DataFrame properly.
第一步:完善get_filters()函数
Your code has started collecting city input, but we need to add input validation (to make sure users enter a valid city) and typically, these bikeshare projects let users filter by month or day of the week too. Here's the completed version:
import time import pandas as pd import numpy as np import datetime as dt CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): print('\n\nHello! Let\'s explore some US bikeshare data!') # Get valid city input city = '' while city not in CITY_DATA: city = input('\nWhich city would you like to explore? Chicago, New York City, or Washington? ').lower() if city not in CITY_DATA: print("Oops, that's not a valid city. Please choose from the three options listed.") # Get valid month input months = ['all', 'january', 'february', 'march', 'april', 'may', 'june'] month = '' while month not in months: month = input('\nWhich month would you like to filter by? Type "all" for no month filter, or choose from January to June: ').lower() if month not in months: print("Invalid month choice. Please pick from the options given.") # Get valid day of week input days = ['all', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'] day = '' while day not in days: day = input('\nWhich day of the week would you like to filter by? Type "all" for no day filter, or choose a day name: ').lower() if day not in days: print("That's not a valid day. Please select from the listed options.") print('-'*40) return city, month, day
Quick notes on this part:
- The
whileloops make sure users can't proceed until they enter a valid option, which prevents errors later when loading data - Using
.lower()standardizes user input, so capitalization doesn't break the matching - We add
alloptions for month and day to let users choose no filtering for those dimensions
第二步:Write a function to load and filter the data
Next, we need a function that takes the filters we collected, loads the correct CSV file, and filters the DataFrame to match user choices:
def load_data(city, month, day): # Load the selected city's data df = pd.read_csv(CITY_DATA[city]) # Convert the Start Time column to datetime format (critical for time-based filtering) df['Start Time'] = pd.to_datetime(df['Start Time']) # Extract month and day of week columns to filter against df['month'] = df['Start Time'].dt.month_name().str.lower() df['day_of_week'] = df['Start Time'].dt.day_name().str.lower() # Filter by month if user didn't choose "all" if month != 'all': df = df[df['month'] == month] # Filter by day of week if user didn't choose "all" if day != 'all': df = df[df['day_of_week'] == day] return df
Key explanations here:
pd.to_datetime()turns raw time strings into datetime objects, which lets us use Pandas'.dtattribute to pull out month/day info easily- Boolean indexing (like
df[df['month'] == month]) is the core way to filter rows in a DataFrame—it keeps only the rows where the condition is true - We lowercase the extracted month/day names to match the standardized user input
第三步:Put it all together
Finally, let's make a main function to run the whole workflow and let users preview the filtered data:
def main(): while True: city, month, day = get_filters() df = load_data(city, month, day) print(f"\nHere's a preview of the filtered data for {city.title()}, month: {month.title()}, day: {day.title()}:") print(df.head()) restart = input('\nWould you like to restart? Enter yes or no.\n').lower() if restart != 'yes': break if __name__ == "__main__": main()
This ties everything together: it collects filters, loads and processes the data, shows a preview, and lets users restart if they want to explore different filters.
内容的提问来源于stack exchange,提问作者TeenTeen

