gpt4 book ai didi

python - Pandas - 有条件地更新下一行的某些列的功能

转载 作者:太空宇宙 更新时间:2023-11-04 02:02:17 26 4
gpt4 key购买 nike

我有一个 csv 文件,其中包含来自不同足球比赛的大量结果。数据类似于下面的示例。result 列可以包含 3 个可能的值:

  • H -> 主队获胜(主队将获得 + 3 分)
  • A -> 客队获胜(客队将获得 + 3 分)
  • D -> 平局(两队均获得+1分)
   HomeTeam    AwayTeam Result
0 FC_Fake ABC_United H
1 Team_123 FC_Berlin A
2 FC_FAKE TEAM_123 D

我想更新文件,让每一行都包含每支球队的总分因为他们在比赛开始时(所以还没有更新比赛的结果行本身)

我使用以下代码更新数据框,因此它包含每个团队的 points_[TEAM_NAME] 虚拟列。

# Teams is a python list I extracted earlier
for team in teams:
df['points_' + team] = 0

目标是转换数据框,使上面的例子变成下面的例子。

(同样,分数应该代表比赛开始时的情况。因此即使 FC_FAKE 在第一行赢得比赛,Points_FC_FAKE 列为 0 )

HomeTeam | AwayTeam | Result  Points_FC_FAKE | Points_TEAM_123 | Points_FC_Berlin |  etc
-------------------------------------------------------------------------------
FC_Fake ABC_United H 0 0 0
Team_123 FC_Berlin A 3 0 0
FC_FAKE Team_123 D 3 0 3

我创建了以下 python 函数,如果它遍历数据框中的所有行,应该解析结果并将正确数量的分数奖励给正确的团队。

def point_updater(x):
if x['Result'] == 'H':
home = x['HomeTeam']
x.shift(-1)['points_' + home] += 3
return x

elif x['Result'] == 'A':
away = x['AwayTeam']
x.shift(-1)['points_' + away] += 3
return x

elif x['Result'] == 'D':
home = x['AwayTeam']
away = x['AwayTeam']
x.shift(-1)['points_' + home] += 1
x.shift(-1)['points_' + away] += 1
return x

问题是当我将此函数应用于数据框时,点不会改变(全部保持为 0)

df = df.apply(point_counter, axis=1)
df['points_FC_Fake'].value_counts()
----
0 2691

有人知道我做错了什么吗?

最佳答案

在某些异常(exception)情况下,我们可以为此使用 iterrows。另外,通过在开始计算之前进行一些清理,我使您的代码更具防错性和通用性:

# Convert to uppercase letters 
df['HomeTeam'] = df['HomeTeam'].str.upper()
df['AwayTeam'] = df['AwayTeam'].str.upper()

# get a list off all the teams in competition
lst_teams = list(set(list(df.HomeTeam.unique()) + list(df.AwayTeam.unique())))

# Create columns for each team
for team in lst_teams:
df[team] = 0

# Iterate over each row and assign correct points
for idx, r in df.iterrows():
if r['Result'] == 'H':
df.loc[[idx], [r['HomeTeam']]] = 3
if r['Result'] == 'A':
df.loc[[idx], [r['AwayTeam']]] = 3
if r['Result'] == 'D':
df.loc[[idx], [r['AwayTeam']]] = 1
df.loc[[idx], [r['HomeTeam']]] = 1

# Shift the rows one down, since points are only available at start of match
df.iloc[:, 3:] = df.iloc[:, 3:].cumsum().shift(1).fillna(0).astype(int)

输出

print(df)
HomeTeam AwayTeam Result ABC_UNITED TEAM_123 FC_FAKE FC_BERLIN
0 FC_FAKE ABC_UNITED H 0 0 0 0
1 TEAM_123 FC_BERLIN A 0 0 3 0
2 FC_FAKE TEAM_123 D 0 0 3 3

关于python - Pandas - 有条件地更新下一行的某些列的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55479146/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com