我想创建列并为在给定“拉力赛”中获胜和失败的每个团队分配一个数字(0 表示失败,1 表示胜利)。每个集会的最后一行将在“积分”列中显示谁获胜。
该图显示了数据的格式以及“结果”列中所需的结果:
我当前的代码是;
def winLoss(x):
if 'A' in x['Points']:
if x.TeamAB == 'A':
return 1
else:
return 0
elif 'B' in x['Points']:
if x.TeamAB == 'B':
return 1
else:
return 0
df['Outcome'] = df.groupby('Rally').apply(winLoss).any()
答案 0 :(得分:0)
通过分组并获取每个组的最后一行 Points
来获取每个集会的获胜者,然后使用多索引来定位过滤并分配 Outcome
:
winners = pd.MultiIndex.from_frame(
df.groupby(['Rally'])['Points']
.last().str.slice(-1).reset_index()
)
df.set_index(['Rally', 'TeamAB'], inplace=True)
df['Outcome'] = 0
df.loc[df.index.isin(winners), 'Outcome'] = 1
df.reset_index(inplace=True)