如何用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_id | location | team |
|---|---|---|
| 123 | home | phillies |
| 123 | away | braves |
| 456 | home | marlins |
| 456 | away | mets |
内容的提问来源于stack exchange,提问作者Larry Burholme
相关产品推荐
相关产品推荐

