如何为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.concatfor each entry, we directly add rows withdf.loc[i]—this avoids messy index conflicts and simplifies the code. - Proper Total/Average Calculation: We use
numeric_only=Trueinsum()andmean()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 todfto 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
相关产品推荐
相关产品推荐

