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

Pandas数据框拆分多值列并按人员汇总时间列值

按人员汇总对应Time值的实现方案

原始数据

Person          Time
1     person1               20
2     person1;person2       60
3     person2;person3       100

现有代码(统计人员出现次数)

df['Person'].str.split(";", expand=True).stack().value_counts()

需求

对每个Person汇总其对应的所有Time值,期望输出:

person1 - 80
person2 - 160
person3 - 100

解决代码

方法一(兼容旧版pandas)

# 拆分Person列并保留原行索引
split_persons = df['Person'].str.split(';', expand=True).stack().reset_index(level=1, drop=True).rename('Person')
# 关联原Time列后按人员分组求和
total_time = df.join(split_persons).groupby('Person')['Time'].sum()
# 按指定格式输出
for person, time in total_time.items():
    print(f"{person} - {time}")

方法二(pandas 0.25+ 简洁写法)

# 拆分Person列为列表后展开,再分组求和
total_time = df.assign(Person=df['Person'].str.split(';')).explode('Person').groupby('Person')['Time'].sum()
# 输出结果
for person, time in total_time.items():
    print(f"{person} - {time}")

说明

  • 方法二中的explode可以直接将拆分后的人员列表拆成多行,每行对应一个人员和原Time值,分组求和后就能得到每个人员的总Time。
  • 两种方法最终都能得到需求的汇总结果,可根据自身pandas版本选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 21:44:49