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

Python中DataFrame按A列分组并取B、C列对应位置最大值的方法

实现方案

核心思路

  • 按A列对DataFrame执行分组操作
  • 对分组后的B、C列做自定义聚合:
    1. 将每个单元格的字符串按分号;拆分,转换为整数列表
    2. 对同一分组内所有列表的对应位置元素取最大值
    3. 将得到的最大值列表重新用分号拼接为字符串

完整代码实现

import pandas as pd

# 构造示例数据
df = pd.DataFrame({
    'A': ['^0hand(%s)leg$', '^-(%s)hand0leg', '^0hand(%s)leg$'],
    'B': ['27;30', '39;30', '24;33'],
    'C': ['42;54', '47;57', '39;54']
})

# 自定义聚合函数:同位置取最大值后拼接
def agg_max_by_pos(series):
    # 把列内每个字符串拆分为整数列表
    num_lists = [list(map(int, s.split(';'))) for s in series]
    # 按位置聚合取最大值
    max_list = [max(pos_items) for pos_items in zip(*num_lists)]
    # 重新拼接为分号分隔的字符串
    return ';'.join(map(str, max_list))

# 按A列分组聚合
result = df.groupby('A', as_index=False).agg({
    'B': agg_max_by_pos,
    'C': agg_max_by_pos
})

print(result)

输出结果

运行代码后得到的结果完全匹配需求:

A      B      C
0  ^0hand(%s)leg$  27;33  42;54
1  ^-(%s)hand0leg  39;30  47;57

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 08:06:05