本文转载至How To Make Your Pandas Loop 71803 Times Faster
结论 - numpy向量化操作最快
标准循环
def soc_loop(leaguedf,TEAM,):
leaguedf['Draws'] = 99999
for row in range(0, len(leaguedf)):
if ((leaguedf['HomeTeam'].iloc[row] == TEAM) & (leaguedf['FTR'].iloc[row] == 'D')) | \
((leaguedf['AwayTeam'].iloc[row] == TEAM) & (leaguedf['FTR'].iloc[row] == 'D')):
leaguedf['Draws'].iloc[row] = 'Draw'
elif ((leaguedf['HomeTeam'].iloc[row] == TEAM) & (leaguedf['FTR'].iloc[row] != 'D')) | \
((leaguedf['AwayTeam'].iloc[row] == TEAM) & (leaguedf['FTR'].iloc[row] != 'D')):
leaguedf['Draws'].iloc[row] = 'No_Draw'
else:
leaguedf['Draws'].iloc[row] = 'No_Game'
pandas内置函数 - 300倍
def soc_iter(TEAM,home,away,ftr):
#team, row['HomeTeam'], row['AwayTeam'], row['FTR']
if [((home == TEAM) & (ftr == 'D')) | ((away == TEAM) & (ftr == 'D'))]:
result = 'Draw'
elif [((home == TEAM) & (ftr != 'D')) | ((away == TEAM) & (ftr != 'D'))]:
result = 'No_Draw'
else:
result = 'No_Game'
return result
apply()方法 - 800倍
pandas向量化操作 - 9,000倍
def soc_iter(TEAM,home,away,ftr):
df['Draws'] = 'No_Game'
df.loc[((home == TEAM) & (ftr == 'D')) | ((away == TEAM) & (ftr == 'D')), 'Draws'] = 'Draw'
df.loc[((home == TEAM) & (ftr != 'D')) | ((away == TEAM) & (ftr != 'D')), 'Draws'] = 'No_Draw'