我有一个大数据帧(500k行,250列)。每排是一场足球赛。 df的一部分示例:
HOME_TEAM AWAY_TEAM GOL_HOME_FT GOL_AWAY_FT ...
1153 Manchester United Swansea City 1 2
1163 Leicester City Everton 2 2
1172 Queens Park Rangers Hull City 0 1
1183 Stoke City Aston Villa 0 1
1193 West Bromwich Albion Sunderland 2 2
现在,对于我的数据框架中的每个不同团队,如果GOL_HOME\u FT>;GOL_AWAY_FT.然后我想计算最大连续真值。
我的代码示例:
for team in list_teams: # list_teams is all the different teams in my df
df_team = df.loc[(df.HOME_TEAM.values == team) | (df.AWAY_TEAM.values == team)]
lst_bool = df_team.GOL_HOME_FT.values > df_team.GOL_AWAY_FT.values
consecutive_true = 0
lst_consecutive_true = []
for i in lst_bool:
if i is True:
consecutive_true += 1
else:
lst_consecutive_true.append(consecutive_true)
consecutive_true = 0
max_consecutive_true = max(lst_consecutive_true)
但是这很慢!我的数据框中有5个不同的团队,所以我必须在数据框中循环5公里的时间。我认为最慢的部分是在过滤数据帧时。 有没有最快的解决办法
您可以尝试类似这样的方法,而不是循环。 这是我使用的数据
我用这个
df['lst_bool'] = df['GOL_HOME_FT']> df['GOL_AWAY_FT']
得到了最后一列然后找到连续的真与假,你可以这样做。
(df.groupby(df.lst_bool.ne(df.lst_bool.shift()).cumsum()).agg({'lst_bool': 'count'})).reset_index(drop=True)
这给了我下面的输出
相关问题 更多 >
编程相关推荐