基于Pandas DataFrame构建Airbnb房源平均价格计算器技术求助
Got it, let's put together this Airbnb average price calculator for you. Since you already have the dataset with all the required features (neighborhood, beds, bathrooms, bedrooms, price), here's a straightforward, step-by-step approach using Python and pandas—super common for this kind of data task:
First, we'll use pandas to load your data and make sure all the required columns are present. This helps catch any typos or missing data early.
import pandas as pd # Replace 'airbnb_listings.csv' with your actual dataset file path df = pd.read_csv('airbnb_listings.csv') # Verify required columns exist required_columns = ['neighborhood', 'beds', 'bathrooms', 'bedrooms', 'price'] if not all(col in df.columns for col in required_columns): raise ValueError("Dataset is missing one or more required columns!") # Quick preview to confirm data looks right print(df[required_columns].head())
Most Airbnb datasets store price as a string with a $ and commas (like "$150" or "$2,500"). We need to convert this to a numeric value so we can calculate averages.
# Remove currency symbols and commas, then convert to float df['price'] = df['price'].replace('[\$,]', '', regex=True).astype(float) # Check for any invalid price values (like NaN) and drop them if needed df = df.dropna(subset=['price'])
This function will take your input parameters, filter the dataset to match those criteria, and return the average price. We'll also handle cases where no matching listings exist to avoid errors.
def get_avg_airbnb_price(neighborhood, beds, bathrooms, bedrooms): # Filter the dataset to only include listings matching your inputs filtered_listings = df[ (df['neighborhood'] == neighborhood) & (df['beds'] == beds) & (df['bathrooms'] == bathrooms) & (df['bedrooms'] == bedrooms) ] # Handle edge case: no matching listings if filtered_listings.empty: return "No matching listings found for these criteria." # Calculate and format the average price avg_price = filtered_listings['price'].mean() return f"Average price: ${avg_price:.2f}"
Try it out with sample inputs to make sure it works:
# Example: Calculate average price for 2-bed, 1.5-bath, 2-bedroom listings in Downtown result = get_avg_airbnb_price(neighborhood="Downtown", beds=2, bathrooms=1.5, bedrooms=2) print(result)
If you want a user-friendly interface instead of running code, you can build a basic GUI with Tkinter:
import tkinter as tk from tkinter import ttk def calculate_and_display(): # Get inputs from the UI fields neighborhood = entry_neighborhood.get() beds = int(entry_beds.get()) bathrooms = float(entry_bathrooms.get()) bedrooms = int(entry_bedrooms.get()) # Run the calculation and update the result label result = get_avg_airbnb_price(neighborhood, beds, bathrooms, bedrooms) label_result.config(text=result) # Set up the window root = tk.Tk() root.title("Airbnb Average Price Calculator") # Create input fields ttk.Label(root, text="Neighborhood:").grid(row=0, column=0, padx=10, pady=5) entry_neighborhood = ttk.Entry(root) entry_neighborhood.grid(row=0, column=1, padx=10, pady=5) ttk.Label(root, text="Number of Beds:").grid(row=1, column=0, padx=10, pady=5) entry_beds = ttk.Entry(root) entry_beds.grid(row=1, column=1, padx=10, pady=5) ttk.Label(root, text="Number of Bathrooms:").grid(row=2, column=0, padx=10, pady=5) entry_bathrooms = ttk.Entry(root) entry_bathrooms.grid(row=2, column=1, padx=10, pady=5) ttk.Label(root, text="Number of Bedrooms:").grid(row=3, column=0, padx=10, pady=5) entry_bedrooms = ttk.Entry(root) entry_bedrooms.grid(row=3, column=1, padx=10, pady=5) # Calculate button btn_calculate = ttk.Button(root, text="Get Average Price", command=calculate_and_display) btn_calculate.grid(row=4, column=0, columnspan=2, padx=10, pady=15) # Result display label label_result = ttk.Label(root, text="", font=('Arial', 10, 'bold')) label_result.grid(row=5, column=0, columnspan=2, padx=10, pady=5) root.mainloop()
内容的提问来源于stack exchange,提问作者Aswin Babu

