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

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

NameCountrySalary
0JohnUSA100
1Steven, IbrahimUK400
2GeorgeFrance100
3Nancy, Mo, KhalilIreland160

Key Details

  • groupby('Country', as_index=False, sort=False):
    • as_index=False ensures Country stays as a regular column instead of becoming the DataFrame index.
    • sort=False preserves 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 Name column, we use ', '.join to concatenate all names in the group with a comma and space.
    • For the Salary column, we use sum to calculate the total salary for the group.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 07:08:12