AnalystPath

Same Opponent for First and Last Match of a Day

PandasHardSenior level~10 min

Problem

You are given one DataFrame `matches`:

| Column | Type |
|-----------|----------|
| home_id | int |
| away_id | int |
| played_at | datetime |

`(home_id, away_id, played_at)` is unique. Each row is a chess match between two players at a moment in time. A player participates as either the home or the away side.

For each player and each calendar day they played, look at their **earliest** match and their **latest** match that day. Report the `player_id` of every player whose first and last match on at least one day were against the **same opponent**.

Return each qualifying player once, in any order, in a column named `player_id`. Assume no player has two matches at the exact same timestamp on the same day.

Input data

Example rows — the live problem includes the full dataset.

matches
home_idaway_idplayed_at
122023-03-01 09:00:00
312023-03-01 12:00:00
212023-03-01 17:00:00
352023-03-01 13:00:00
532023-03-01 20:00:00

Expected output

Your answer should return 3 rows with the columns player_id.

Starter code (Pandas (Python))

import pandas as pd

def same_opponent_first_and_last(matches) -> pd.DataFrame:
    # Your code here
    return matches

Solve this Pandas question free

Write Pandas (Python) and run it instantly in your browser — even on your phone. No signup needed to try.

Solution & explanation

Create a free account to unlock the optimal solution, a step-by-step explanation, and the hidden test cases that grade your answer.

Sign up free to unlock

Related Pandas questions