You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在DataFrame中基于球队列获取上一场比赛日期并计算休息天数

Calculating Rest Days for Football Teams

First up, let's make sure your Matchday column is formatted as a datetime—this is crucial for accurate date difference calculations:

import pandas as pd

# Convert Matchday to datetime if it's not already
df['Matchday'] = pd.to_datetime(df['Matchday'])

Next, sort your DataFrame by team and match date. This ensures we're comparing each match to the immediately preceding one for the same team, which is exactly what we need:

df = df.sort_values(by=['Team', 'Matchday'])

Now for the core calculation—we'll use groupby to isolate each team's match history, then diff() to find the gap between consecutive matches:

# Calculate days since the last match for each team
df['Rest_Days'] = df.groupby('Team')['Matchday'].diff().dt.days

Breakdown of how this works:

  • groupby('Team') splits the data so we only look at one team's matches at a time
  • diff() computes the time difference between the current match's date and the previous match's date within each team's group
  • .dt.days converts the raw timedelta result into a clean numeric day count
  • The first match for every team will show NaN in Rest_Days (since there's no prior match to compare), which aligns perfectly with your requirement for first-time entries.

Example Output:

If your input data looks like this:

MatchdayTeamHome_Away
2022-08-05Arsenal FCHome
2022-08-07Leicester CityAway
2022-08-13Arsenal FCHome
2022-08-13Leicester CityAway

After running the code, you'll get:

MatchdayTeamHome_AwayRest_Days
2022-08-05Arsenal FCHomeNaN
2022-08-13Arsenal FCHome8.0
2022-08-07Leicester CityAwayNaN
2022-08-13Leicester CityAway6.0

Which matches the example you provided!

If you prefer to replace NaN with a specific value (like 0 for clarity), just add:

# Optional: Replace NaN with 0 or another value
df['Rest_Days'] = df['Rest_Days'].fillna(0)

内容的提问来源于stack exchange,提问作者Morten Ravn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 15:43:16