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

如何用Pandas按条件重塑数据集:合并主客场队列为对应位置的队名列

数据集转换方案

原始数据集

import pandas as pd

df = pd.DataFrame({'game_id' : [123,123,456,456],
                   'location' : ['home', 'away','home', 'away'],
                   'away_team' : ['braves', 'braves', 'mets', 'mets'],
                   'home_team' : ['phillies', 'phillies', 'marlins', 'marlins']})

需求说明

将away_team和home_team合并为team列:

  • 当location为home时,team取home_team的值
  • 当location为away时,team取away_team的值
    最终保留game_id、location、team三列。

解决方案

方法1:使用numpy.where(推荐,高效简洁)

import numpy as np

# 添加team列
df['team'] = np.where(df['location'] == 'home', df['home_team'], df['away_team'])
# 筛选需要的列
result_df = df[['game_id', 'location', 'team']]

方法2:使用apply(适合复杂逻辑扩展)

def map_team(row):
    return row['home_team'] if row['location'] == 'home' else row['away_team']

df['team'] = df.apply(map_team, axis=1)
result_df = df[['game_id', 'location', 'team']]

方法3:使用lookup

# 把location映射为对应的列名
df['target_col'] = df['location'].replace({'home': 'home_team', 'away': 'away_team'})
# 根据映射列名取值
df['team'] = df.lookup(df.index, df['target_col'])
result_df = df[['game_id', 'location', 'team']]

转换后结果

game_idlocationteam
123homephillies
123awaybraves
456homemarlins
456awaymets

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 02:52:20