如何修改Pandas DataFrame列名并设置从1起始的序号列及格式化输出?
Solution to Fix Pandas Output Formatting Issues
Got it, let's tackle those three formatting problems you're facing with your Pandas output. Here's a step-by-step adjusted code that'll get your results matching the desired style:
Step-by-Step Code Implementation
import pandas as pd # 1. Load the dataset df = pd.read_csv("past_transacted_px.csv") # 2. Apply your filtering conditions (adjust these to match your actual input criteria) # Example: Filter for EXECUTIVE flats in area A, resale price between 100k and 300k filtered_data = df[ (df["flat_type"] == "EXECUTIVE") & (df["town"] == "A") & (df["resale_price"].between(100000, 300000)) ] # 3. Fix continuous serial number (No. column) # Reset index to drop original indices, then create a 1-based sequence filtered_data = filtered_data.reset_index(drop=True) filtered_data["No."] = filtered_data.index + 1 # 4. Rename columns to the required format filtered_data = filtered_data.rename(columns={ "block": "Block", "street_name": "Street Name", "storey_range": "Storey Range", "floor_area_sqm": "Floor Area Sqm", "resale_price": "Resale Price" }) # 5. Format numeric values # Convert floor area to integer to remove decimals filtered_data["Floor Area Sqm"] = filtered_data["Floor Area Sqm"].astype(int) # Add thousand separators to resale price filtered_data["Resale Price"] = filtered_data["Resale Price"].apply(lambda x: f"{int(x):,}") # 6. Print the final formatted output print(f"The EXECUTIVE flats available in A are:") # Emphasize the header as required print("**No. Block Street Name Storey Range Floor Area Sqm Resale Price**") # Iterate through rows to print with emphasized serial number and values for _, row in filtered_data.iterrows(): print(f"**{row['No.']}** {row['Block']} {row['Street Name']} {row['Storey Range']} **{row['Floor Area Sqm']} {row['Resale Price']}**")
Key Fixes Explained
- Continuous Serial Number: Using
reset_index(drop=True)clears the original DataFrame indices, then we create a newNo.column starting from 1 withindex + 1. - Column Name Adjustment: The
rename()method maps the original column names to the user-friendly, capitalized format you need. - Numeric Formatting:
- Convert
floor_area_sqmto integer to eliminate decimal points. - Use a lambda function with f-string formatting to add thousand separators to
resale_price.
- Convert
- Output Styling: We use asterisks (
**) to emphasize the header, serial numbers, and formatted numeric values, matching your expected output style.
内容的提问来源于stack exchange,提问作者Dearest
相关产品推荐
相关产品推荐

