Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 14.8 — Grouping, Joining and Reshaping
Python · Example 2 of 3

merge, concat and a method chain

Change how="left" to how="outer" in the second line and see customer 12 appear with no order.

groupby splits a table into groups and summarises each, merge joins two tables on a shared key like a SQL join, concat stacks tables, and pivot_table turns rows into a grid. Together they answer most business questions about a table.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Given sales with shop and amount columns, compute the average amount per shop.

02

Left-merge a students frame (id, name) with marks (id, mark) and list who has no mark.

03

Write a chain that keeps rows where amount > 10, sorts by amount descending and keeps the first row.

04

Given sales with columns shop (A, B, A, B) and amount (10, 20, 30, 60), add a column share holding each row's amount as a fraction of its own shop's total, using transform.

Explain it without notes

01

Explain split-apply-combine and write a groupby that gives the total revenue per city.

02

What is the difference between inner, left and outer merges? Give a case for each.

03

When do you use concat and when merge?

04

What does a pivot table give you that a groupby does not?

05

After a left merge your row count grows from 1,000 to 1,400 and revenue totals jump. What happened and how do you detect and prevent it?

06

What is the difference between groupby(...).agg(...) and groupby(...).transform(...), and between count and size?

merge, concat and a method chain
Sign in to run this example in your browser.

Expected output

   order  cust  amount  name
0      1    10   250.0  Asha
1      2    11    80.0   Ben
2      3    10    40.0  Asha
   order  cust  amount  name
0      1    10   250.0  Asha
1      2    11    80.0   Ben
2      3    10    40.0  Asha
3      4    99    15.0   NaN
(5, 3)
 order name  amount
     1 Asha   250.0
     2  Ben    80.0
     5 Chen    60.0