如何在Python DataFrame中用np.where实现多条件比赛结果判断
足球比赛结果判断的正确实现方案
你之前用多次np.where导致结果被覆盖,是因为每次单独赋值会全量更新列,没有保留之前的分支结果。以下几种方法可以正确实现分支逻辑:
方法一:嵌套np.where
通过嵌套np.where实现多分支判断,一次完成赋值,避免覆盖问题:
import pandas as pd import numpy as np # 示例DataFrame df = pd.DataFrame({ 'home': ['A队', 'B队', 'C队'], 'away': ['D队', 'E队', 'F队'], 'scorehome': [3, 1, 2], 'scoreaway': [1, 1, 3] }) # 嵌套判断:先主队胜,再客队胜,剩余为平局 df['result'] = np.where( df['scorehome'] > df['scoreaway'], '1', np.where(df['scorehome'] < df['scoreaway'], '2', 'X') )
方法二:使用np.select
适合多条件场景,定义条件列表和对应结果列表,最后指定默认值:
conditions = [ df['scorehome'] > df['scoreaway'], df['scorehome'] < df['scoreaway'] ] values = ['1', '2'] # 匹配条件返回对应值,不满足任何条件返回默认值'X' df['result'] = np.select(conditions, values, default='X')
方法三:使用apply(小数据量适用)
自定义判断函数,逐行处理数据,逻辑直观但大数据量下效率略低:
def judge_result(row): if row['scorehome'] > row['scoreaway']: return '1' elif row['scorehome'] < row['scoreaway']: return '2' else: return 'X' df['result'] = df.apply(judge_result, axis=1)
内容的提问来源于stack exchange,提问作者Terra1
相关产品推荐
相关产品推荐

