Question Details

No question body available.

Tags

python pandas date date-difference

Answers (1)

April 17, 2026 Score: 0 Rep: 65 Quality: Low Completeness: 80%

You can first melt the dataframe to have one row per team and date, then sort by date, then calculate the difference in days using groupby and diff, and finally pivot back to the original format:

import pandas as pd

def calculatedaysdiff(df: pd.DataFrame) -> pd.DataFrame: result = df.copy() result["Date"] = pd.todatetime(result["Date"]) result["row"] = range(len(result)) longdf = result.melt( idvars=["row", "Date"], valuevars=["teamhome", "teamaway"], varname="side", valuename="team", ) longdf["daysdiff"] = ( longdf.sortvalues(["team", "Date", "row"]) .groupby("team", sort=False)["Date"] .diff() .dt.days.fillna(0) # fillna can be removed if you want to use NaN for the first occurrence .astype(int) ) diffdf = longdf.pivot(index="row", columns="side", values="daysdiff").rename( columns={"teamhome": "homediff", "teamaway": "awaydiff"} )[["homediff", "awaydiff"]] return result.join(diffdf, on="row").drop(columns="row")

def main() -> None: import io

data = """\ Date,teamhome,teamaway 2026-05-10,Tottenham,Arsenal 2026-05-11,Liverpool,West Ham 2026-05-13,West Ham,Chelsea 2026-05-13,Arsenal,Liverpool """ df = pd.readcsv(io.StringIO(data)) resultdf = calculatedaysdiff(df) print(resultdf) """\ Date teamhome teamaway homediff away_diff 0 2026-05-10 Tottenham Arsenal 0 0 1 2026-05-11 Liverpool West Ham 0 0 2 2026-05-13 West Ham Chelsea 2 0 3 2026-05-13 Arsenal Liverpool 3 2 """

if name == "main": main()