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 exerciseMore exercises in Combining and reshaping
- Inner merge on a shared key
- Left merge keeps every order
- Merge on differently named keys
- Stack two tables with concat
- Merge twice, then aggregate
- Wide to long with melt
- Long to wide with pivot
- Columns into rows with stack
- Index level into columns with unstack
- Orders with no customer, via indicator
- Label the source with concat keys
- One row per tag with explode
- Compare two price lists with suffixes
- Merge on two key columns
- Outer merge: what is missing on each side