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

如何修改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 new No. column starting from 1 with index + 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_sqm to integer to eliminate decimal points.
    • Use a lambda function with f-string formatting to add thousand separators to resale_price.
  • Output Styling: We use asterisks (**) to emphasize the header, serial numbers, and formatted numeric values, matching your expected output style.

内容的提问来源于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 08:04:50