如果满足条件,则为子组分配值

时间:2021-04-19 21:32:43

标签: python pandas group-by

我想创建列并为在给定“拉力赛”中获胜和失败的每个团队分配一个数字(0 表示失败,1 表示胜利)。每个集会的最后一行将在“积分”列中显示谁获胜。

该图显示了数据的格式以及“结果”列中所需的结果: The image shows how the data is formatted and the desired result is in the 'Outcome' column

我当前的代码是;

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()

1 个答案:

答案 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)