Pandasdrill

Level 4: Combining and reshaping Exercise 61 of 102

Merge a table with itself

A pandas exercise from Pandasdrill. Solve it with a Python editor in your browser running real pandas, and it is checked the moment you submit.

The task

In `staff`, `manager_id` holds the `emp_id` of the person's manager; the person at the top has none. Return one row for every employee who has a manager, with the columns `name` and `manager` (the manager's name). Row labels and row order do not matter.

What this exercise teaches

A self merge treats one table as two: here the employees on the left and the same people as managers on the right. The inner merge drops the person without a manager, because no emp_id matches a missing manager_id. Swapping the two keys gives the reverse relation, each manager with their reports.

A hint if you get stuck

Merge staff with staff: the left side plays the employee and the right side the manager, so the keys are left_on="manager_id" and right_on="emp_id". suffixes tells the two name columns apart.

Try it now, free, no account needed

Your first 8 exercises on Pandasdrill are free. Open it on the practice page, solve it, and get instant feedback with a hint. A free account adds the worked solution; Pro unlocks every exercise, timed mode and the certificate.

Open this exercise

More exercises in Combining and reshaping