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

Pandas中如何对主客场互换的球队配对的比赛场数合并求和

你可以通过生成不区分主客场的配对分组键,分组求和后映射回原数据实现需求,代码如下:

import pandas as pd
import numpy as np

# 方法1:小数据量场景,逻辑直观
# 生成无顺序的配对键
most_often['pair_key'] = most_often.apply(lambda row: '_'.join(sorted([row['home_team'], row['away_team']])), axis=1)

# 方法2:大数据量场景,向量化操作效率更高
# most_often['pair_key'] = np.minimum(most_often['home_team'], most_often['away_team']) + '_' + np.maximum(most_often['home_team'], most_often['away_team'])

# 按配对键统计总场次
pair_total = most_often.groupby('pair_key')['how_many'].sum().reset_index(name='total')

# 合并总场次到原表
most_often = most_often.merge(pair_total, on='pair_key')

# 替换原场次列,删除辅助列
most_often['how_many'] = most_often['total']
most_often = most_often.drop(columns=['pair_key', 'total'])

运行上述代码后,most_often表中的how_many列就会更新为两队对阵的总场次,完全匹配你给出的预期输出效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 19:24:03