~/learn/Pandas · Merging & reshaping

Merging and reshaping

Joins, pivots and melts.

9 min readlesson 5 of 13mergepivot_tablemelt

why this matters

Your data rarely lives in one file. merge joins tables the same way SQL JOIN does.

merge is the pandas join: name the key and the kind of join you want. left keeps every row on the left, inner keeps only matches.

python · editable
loading editor…

pivot_table reshapes long data into a matrix, aggregating duplicates as it goes.

python · editable
loading editor…

melt does the reverse, turning wide columns back into rows.

python · editable
loading editor…

Watch the row count

Check row counts before and after a merge. If it grows unexpectedly, your key has duplicates.

key takeaways

  • pd.merge(a, b, on="key") joins tables.
  • how="left" keeps all rows from a.
  • concat stacks tables on top of each other.

check your understanding

What's the SQL equivalent of pd.merge(orders, customers, on="customer", how="left")?

free practice

Build confidence with a question you can solve without Pro.