如何在多变量表格中合并重复项并求和
Solutions to Merge Duplicate Class Entries and Sum Numeric Columns
I've got you covered! Here are three straightforward methods to achieve your desired result, depending on the tool you're using:
1. Excel/Google Sheets (Pivot Table Method)
This is the easiest built-in way for spreadsheet users:
- Step 1: Select your entire dataset (including headers: Item, Class, A, B, C).
- Step 2: In Excel, go to
Insert > PivotTable; in Google Sheets, go toData > Pivot table. - Step 3: In the PivotTable editor:
- Drag the
Classfield to the Rows section. - Drag
A,B, andCeach to the Values section. By default, they might show as "Count"—click the dropdown for each value field and selectSuminstead.
- Drag the
- Result: You’ll get a clean table with merged Class names and summed values for A, B, C exactly as you wanted.
2. Python (Pandas Library)
If you prefer code-based data manipulation, pandas makes this a breeze:
import pandas as pd # Load your data (replace this with reading from a file if needed) data = { 'Item': ['AA', 'BB', 'CC', 'DD', 'EE', 'FF'], 'Class': ['Apple', 'Apple', 'Pear', 'Orange', 'Pear', 'Orange'], 'A': [1, 2, 7, 8, 10, 20], 'B': [2, 8, 9, 9, 8, 12], 'C': [4, 9, 10, 0, 2, 3] } df = pd.DataFrame(data) # Group by Class and sum the numeric columns summary_df = df.groupby('Class')[['A', 'B', 'C']].sum().reset_index() # Print or export the result print(summary_df)
Running this code will output:
Class A B C 0 Apple 3 10 13 1 Orange 28 21 3 2 Pear 17 15 12
3. SQL (For Database-Stored Data)
If your data lives in a SQL database, use this query to group and sum:
SELECT Class, SUM(A) AS A, SUM(B) AS B, SUM(C) AS C FROM your_table_name GROUP BY Class ORDER BY Class;
Just replace your_table_name with the actual name of your table, and this will return the aggregated results.
All three methods will give you exactly the output you’re looking for. Pick the one that fits your workflow best!
内容的提问来源于stack exchange,提问作者Lennon Lee
相关产品推荐
相关产品推荐

