Pandas按Country分组合并Name列文本并求和Salary列的实现方案
Solution for Grouping by Country with Merged Names and Summed Salaries
Nice start with getting the salary sums grouped by Country! To also merge the Name values into comma-separated strings for each group, you can use pandas' agg() method—this lets you apply different aggregation logic to different columns in a single groupby call.
Complete Code
import pandas as pd # Your original DataFrame df = pd.DataFrame( {'Name': {0: 'John',1: 'Steven',2: 'Ibrahim',3: 'George',4: 'Nancy',5: 'Mo',6: 'Khalil'}, 'Country': {0: 'USA',1: 'UK',2: 'UK',3: 'France',4: 'Ireland',5: 'Ireland',6: 'Ireland'}, 'Salary': {0: 100, 1: 200, 2: 200, 3: 100, 4: 50, 5: 100, 6: 10}} ) # Group by Country, merge names, sum salaries, keep original order result = df.groupby('Country', as_index=False, sort=False).agg( Name=('Name', ', '.join), Salary=('Salary', 'sum') ) print(result)
Output
| Name | Country | Salary | |
|---|---|---|---|
| 0 | John | USA | 100 |
| 1 | Steven, Ibrahim | UK | 400 |
| 2 | George | France | 100 |
| 3 | Nancy, Mo, Khalil | Ireland | 160 |
Key Details
groupby('Country', as_index=False, sort=False):as_index=Falseensures Country stays as a regular column instead of becoming the DataFrame index.sort=Falsepreserves the order in which countries first appeared in your original data (matches your desired output). Remove this if you want results sorted alphabetically by Country.
agg(): This method lets you define column-specific aggregation rules. Here:- For the
Namecolumn, we use', '.jointo concatenate all names in the group with a comma and space. - For the
Salarycolumn, we usesumto calculate the total salary for the group.
- For the
内容的提问来源于stack exchange,提问作者Ibrahim Ayoup
相关产品推荐
相关产品推荐

