3 回答
TA贡献1829条经验 获得超7个赞
在某些例外情况下,我们可以使用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
TA贡献1796条经验 获得超4个赞
可能有一种更简洁的方式来执行这些操作,但现在应该足够了。您可以使用df.replace()将Result键映射到它们的关联值,然后使用pd.concat()和pd.DataFrame.pivot()实现您想要的结果:
import pandas as pd
df = pd.DataFrame({'HomeTeam': ['FC_Fake','Team_123','FC_Fake'], 'AwayTeam': ['ABC_United','FC_Berlin','Team_123'], 'Result': ['H','A','D']})
remap = df.replace({'H': 3, 'A': 3, 'D': 1})
new = pd.concat([remap.pivot(columns='HomeTeam', values='Result'), remap.pivot(columns='AwayTeam', values='Result')], axis=1).shift(1).fillna(0).astype(int).cumsum()
final = pd.concat([df, new], axis=1)
产量:
HomeTeam AwayTeam Result FC_Fake Team_123 ABC_United FC_Berlin \
0 FC_Fake ABC_United H 0 0 0 0
1 Team_123 FC_Berlin A 3 0 3 0
2 FC_Fake Team_123 D 3 3 3 3
Team_123
0 0
1 0
2 0
TA贡献1824条经验 获得超6个赞
将您的功能更改为:
def point_updater(x):
if x['Result'] == 'H':
home = x['HomeTeam']
x['points_' + home] += 3
return x
elif x['Result'] == 'A':
away = x['AwayTeam']
x['points_' + away] += 3
return x
elif x['Result'] == 'D':
home = x['HomeTeam']
away = x['AwayTeam']
x['points_' + home] += 1
x['points_' + away] += 1
return x
然后在代码的末尾添加:
df = df.apply(point_updater,axis=1)
for team in teams:
df["points_" + team]= df["points_" + team].cumsum()
添加回答
举报