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

如何为Pandas DataFrame数值添加$符号并将Names列设为索引?

Solution to Format Pandas DataFrame as Required

Got it, let's fix your code to generate the exact formatted table you want. Here's the revised code with key improvements explained:

import pandas as pd

df = pd.DataFrame(columns=["Names", "Cider", "Juice", "Subtotal(Cider)", "Subtotal(Juice)", "Total"])
people_ordered = input('How many people ordered? ')  # type str

'''Create the table from user input'''
for i in range(int(people_ordered)):
    names = input(f"Enter the name of Person #{i + 1}: ")
    cider_ordered = float(input(f"How many orders of cider did {names} have? "))
    juice_ordered = float(input(f"How many orders of juice did {names} have? "))

    # Calculate subtotals and total
    cider_sub = 5.50 * cider_ordered
    juice_sub = 4.50 * juice_ordered
    total = cider_sub + juice_sub

    # Append each person's data to the DataFrame
    df.loc[i] = [names, cider_ordered, juice_ordered, cider_sub, juice_sub, total]

# Add Total row
total_row = df.sum(numeric_only=True)
total_row["Names"] = "Total"
df.loc["Total"] = total_row

# Add Average row
average_row = df[:int(people_ordered)].mean(numeric_only=True)
average_row["Names"] = "Average"
df.loc["Average"] = average_row

# Format columns with $ for monetary values
monetary_cols = ["Subtotal(Cider)", "Subtotal(Juice)", "Total"]
df[monetary_cols] = df[monetary_cols].applymap(lambda x: f"$ {x:.2f}")

# Format Cider and Juice columns: integers for regular rows, 2 decimals for Average
def format_qty(value, is_average):
    if is_average:
        return f"{value:.2f}"
    else:
        return f"{int(value)}"

# Apply formatting to Cider column
df["Cider"] = df.apply(lambda row: format_qty(row["Cider"], row["Names"] == "Average"), axis=1)
# Apply formatting to Juice column
df["Juice"] = df.apply(lambda row: format_qty(row["Juice"], row["Names"] == "Average"), axis=1)

# Set Names as the index
df = df.set_index("Names")

# Print the formatted table
print(df.to_string())

Key Changes Explained:

  • Cleaner Row Appending: Instead of using pd.concat for each entry, we directly add rows with df.loc[i]—this avoids messy index conflicts and simplifies the code.
  • Proper Total/Average Calculation: We use numeric_only=True in sum() and mean() to skip the non-numeric "Names" column, then explicitly set the "Names" value for these summary rows.
  • Monetary Value Formatting: Target the 3 price columns and use applymap() to add the $ symbol and ensure all values show 2 decimal places, matching your target table.
  • Quantity Formatting: A custom function handles "Cider" and "Juice" values—showing integers for regular customers and 2 decimal places for the Average row.
  • Correct Index Setup: We assign the result of set_index("Names") back to df to make "Names" the official index, which aligns with your desired table structure.
  • Readable Printing: Using df.to_string() ensures the table prints in a fully aligned, non-truncated format that matches your target output.

When you run this code, it will generate exactly the formatted table you specified, with proper $ symbols, aligned values, and "Names" as the index.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:20:29