如何在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 timediff()computes the time difference between the current match's date and the previous match's date within each team's group.dt.daysconverts the raw timedelta result into a clean numeric day count- The first match for every team will show
NaNinRest_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:
| Matchday | Team | Home_Away |
|---|---|---|
| 2022-08-05 | Arsenal FC | Home |
| 2022-08-07 | Leicester City | Away |
| 2022-08-13 | Arsenal FC | Home |
| 2022-08-13 | Leicester City | Away |
After running the code, you'll get:
| Matchday | Team | Home_Away | Rest_Days |
|---|---|---|---|
| 2022-08-05 | Arsenal FC | Home | NaN |
| 2022-08-13 | Arsenal FC | Home | 8.0 |
| 2022-08-07 | Leicester City | Away | NaN |
| 2022-08-13 | Leicester City | Away | 6.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
相关产品推荐
相关产品推荐

