You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改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 using range(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=True to apply changes directly), avoiding the mistake of overwriting the renamed DataFrame with unfiltered original columns.
  • Value Formatting:
    • Convert Floor Area Sqm to integers with astype(int) to remove decimal places and match the desired whole number output.
    • Format Resale Price with thousand separators using a lambda function and Python's formatted string literals (f"{x:,}").
  • Clean Output: Using to_string(index=False) when printing removes the default Pandas index, so only your custom No. column is displayed.

内容的提问来源于stack exchange,提问作者Dearest

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:58:51