如何修改Pandas DataFrame列名并新增从1起始的序号列
Fixing Pandas Resale Price Data Output Issues
Let's get your code aligned with the desired output by addressing the three key issues: custom sequential numbering, correct column names, and formatted values. Here's the step-by-step adjusted solution:
Full Corrected Code
import pandas as pd # Load the dataset df = pd.read_csv("past_transacted_px.csv") # User input variables (assuming these are defined elsewhere in your code) # town_choice = "A" # desired_flat = "EXECUTIVE" # min_price = 150000 # max_price = 250000 # Step 1: Filter the data based on user criteria first flat_list = df.loc[ (df['town'] == town_choice) & (df['flat_type'] == desired_flat) & (df['resale_price'] >= min_price) & (df['resale_price'] <= max_price) ].copy() # Use .copy() to avoid SettingWithCopyWarning # Step 2: Add sequential No. column starting from 1 flat_list['No.'] = range(1, len(flat_list) + 1) # Step 3: Rename columns to the desired names flat_list.rename( columns={ "block": "Block", "street_name": "Street Name", "storey_range": "Storey Range", "floor_area_sqm": "Floor Area Sqm", "resale_price": "Resale Price" }, inplace=True ) # Step 4: Format values - area to integer, price with thousand separators flat_list['Floor Area Sqm'] = flat_list['Floor Area Sqm'].astype(int) flat_list['Resale Price'] = flat_list['Resale Price'].apply(lambda x: f"{x:,}") # Step 5: Reorder columns to match desired output desired_columns = ['No.', 'Block', 'Street Name', 'Storey Range', 'Floor Area Sqm', 'Resale Price'] df_final = flat_list[desired_columns] # Print the result print(f'The {desired_flat} flats available in {town_choice} are:') print(df_final.to_string(index=False)) # Disable default index in output
Key Fixes Explained
- Sequential Numbering: Instead of relying on the original DataFrame index, we generate a new
No.column starting at 1 usingrange(1, len(flat_list)+1). This ensures numbering always starts from 1 regardless of the original index values. - Correct Column Names: We rename columns after filtering the data (using
inplace=Trueto apply changes directly), avoiding the mistake of overwriting the renamed DataFrame with unfiltered original columns. - Value Formatting:
- Convert
Floor Area Sqmto integers withastype(int)to remove decimal places and match the desired whole number output. - Format
Resale Pricewith thousand separators using a lambda function and Python's formatted string literals (f"{x:,}").
- Convert
- Clean Output: Using
to_string(index=False)when printing removes the default Pandas index, so only your customNo.column is displayed.
内容的提问来源于stack exchange,提问作者Dearest
相关产品推荐
相关产品推荐

