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

如何对分组后的pandas DataFrame执行相减操作并生成指定格式结果

如何对分组后的pandas DataFrame执行相减操作并生成指定格式结果

没问题,我来一步步帮你实现这个需求~

下面给你两种可行的方案,你可以根据实际数据情况选择:

方案一:分组+自定义处理函数(通用型,适配任意玩家顺序)

这种方法不需要提前知道玩家ID,只要每个match_id+round分组下恰好有2条玩家数据就能正常工作。如果想让分数高的玩家作为home,我们可以先给数据按分数降序排序:

import pandas as pd

# 构造示例数据(实际使用时替换成你的数据加载代码,比如pd.read_csv())
df = pd.DataFrame({
    'match_id': [5890]*6,
    'player_id': [3750,3750,3750,2366,2366,2366],
    'round': [1,2,3,1,2,3],
    'points': [10,10,10,9,9,9],
    'A': [0,0,0,0,0,0],
    'B': [0,0,8,0,0,0],
    'C': [0,0,0,0,0,0],
    'D': [3,1,0,5,5,2],
    'E': [1,0,1,0,0,0]
})

# 可选:按match_id、round排序,且同组内分数高的玩家排前面(作为home)
df = df.sort_values(['match_id', 'round', 'points'], ascending=[True, True, False])

# 定义分组后的处理逻辑
def process_player_group(group):
    # 取组内第一行作为home玩家,第二行作为away玩家
    home_row = group.iloc[0]
    away_row = group.iloc[1]
    
    # 组装结果行
    result_row = pd.Series()
    result_row['match_id'] = home_row['match_id']
    result_row['round'] = home_row['round']
    result_row['points_home'] = home_row['points']
    result_row['points_away'] = away_row['points']
    # 计算A-E列的差值(home值 - away值)
    for col in ['A', 'B', 'C', 'D', 'E']:
        result_row[col] = home_row[col] - away_row[col]
    return result_row

# 按match_id和round分组,应用处理函数,最后重置索引
final_result = df.groupby(['match_id', 'round']).apply(process_player_group).reset_index(drop=True)
print(final_result)

方案二:用unstack拆分玩家数据(更直接,适合已知玩家ID的场景)

如果你已经明确知道home和away对应的玩家ID(比如示例中的3750和2366),可以用unstack快速拆分两组数据,再计算差值:

import pandas as pd

# 构造示例数据
df = pd.DataFrame({
    'match_id': [5890]*6,
    'player_id': [3750,3750,3750,2366,2366,2366],
    'round': [1,2,3,1,2,3],
    'points': [10,10,10,9,9,9],
    'A': [0,0,0,0,0,0],
    'B': [0,0,8,0,0,0],
    'C': [0,0,0,0,0,0],
    'D': [3,1,0,5,5,2],
    'E': [1,0,1,0,0,0]
})

# 按match_id、round、player_id设置索引,然后unstack拆分玩家数据
unstacked_data = df.set_index(['match_id', 'round', 'player_id']).unstack()

# 构建最终结果DataFrame
final_result = pd.DataFrame()
# 提取match_id和round列
final_result['match_id'] = unstacked_data.index.get_level_values(0)
final_result['round'] = unstacked_data.index.get_level_values(1)
# 提取两个玩家的points
final_result['points_home'] = unstacked_data['points'][3750].values
final_result['points_away'] = unstacked_data['points'][2366].values
# 计算A-E列的差值(home - away)
for col in ['A', 'B', 'C', 'D', 'E']:
    final_result[col] = unstacked_data[col][3750] - unstacked_data[col][2366]

# 重置索引
final_result = final_result.reset_index(drop=True)
print(final_result)

运行任意一种方案,都能得到你想要的输出结果哦~

备注:内容来源于stack exchange,提问作者HJA24

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 14:03:10