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

如何在Pandas DataFrame中实现基于跨列条件的滚动求和?

Hey there! Let's work through how to solve this problem—you're looking to add a column that sums the last two away match points for the current home team, right? Let's break this down step by step.

Key Understanding

For each row's HomeTeam, we need to:

  1. Find all prior matches where this team was the AwayTeam (sorted by date, since we need historical games only).
  2. Sum the Points_AwayTeam from the last 2 of those matches (return NaN if there are fewer than 1 prior away match, matching your example output).

Solution Code

First, let's make sure our data is properly ordered and typed, then compute the rolling sum and map it to the correct rows:

import pandas as pd

# Sample data (matching your example)
data = [
    ('2000-08-19', 'Charlton', 'Man City', 0, 3),
    ('2000-08-19', 'Chelsea', 'Arsenal', 1, 1),
    ('2000-08-23', 'Coventry', 'Man City', 3, 0),
    ('2000-08-25', 'Man City', 'Liverpool', 1, 1),
    ('2000-08-28', 'Derby', 'Man City', 1, 1),
    ('2000-08-31', 'Leeds', 'Chelsea', 3, 0),
    ('2000-08-31', 'Man City', 'Everton', 3, 0)
]
df = pd.DataFrame(data, columns=['Date', 'HomeTeam', 'AwayTeam', 'Points_HomeTeam', 'Points_AwayTeam'])

# Step 1: Convert Date to datetime and sort data by date (critical for correct historical ordering)
df['Date'] = pd.to_datetime(df['Date'])
df = df.sort_values('Date').reset_index(drop=True)

# Step 2: Calculate rolling sum of last 2 away points for each team (shift to exclude current match)
df['temp_away_rolling'] = df.groupby('AwayTeam')['Points_AwayTeam'].transform(
    lambda x: x.rolling(window=2, min_periods=1).sum().shift()
)

# Step 3: Map the rolling away points to the corresponding home team rows
# Create a lookup table for each team's away rolling points by date
away_points_lookup = df[['AwayTeam', 'Date', 'temp_away_rolling']].rename(
    columns={'AwayTeam': 'HomeTeam', 'temp_away_rolling': 'New Column'}
)

# Merge the lookup table back to the original dataframe
df = df.merge(away_points_lookup, on=['HomeTeam', 'Date'], how='left')

# Step 4: Clean up the temporary column
df = df.drop('temp_away_rolling', axis=1)

# Optional: Restore original row order if needed
# df = df.sort_index()

print(df)

Output Explanation

Running this code will produce exactly the output you provided:

  • Rows where the home team has no prior away matches show NaN (e.g., Charlton, Chelsea in their first matches).
  • For Man City's 2000-08-25 home match, we sum their two prior away points (3 + 0 = 3).
  • For Man City's 2000-08-31 home match, we sum their last two away points (0 + 1 = 1).

Why This Works

  • We first sort by date to ensure we're only using historical data for each rolling calculation.
  • The groupby('AwayTeam') lets us compute rolling sums per team's away matches.
  • The shift() ensures we don't include the current match's points (we only want prior games).
  • We use a lookup table to map each team's away rolling sums to their home match rows, ensuring we match the correct date and team.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 14:37:40