Last updated

Combining DataFrames

Definition: You often need data from more than one table. concat stacks tables together; merge joins them on a shared key column — exactly like a SQL JOIN.

Example 1 — stack rows with concat

import pandas as pd
a = pd.DataFrame({"name": ["Sam", "Alex"]})
b = pd.DataFrame({"name": ["Jo", "Pat"]})
print(pd.concat([a, b], ignore_index=True))

Example 2 — join on a key with merge

import pandas as pd
people = pd.DataFrame({"id": [1, 2], "name": ["Sam", "Alex"]})
cities = pd.DataFrame({"id": [1, 2], "city": ["London", "Paris"]})
print(pd.merge(people, cities, on="id"))

The two tables are matched up by the shared id column, giving one combined table.

Merge types

  • inner (default) — only ids found in both tables
  • left — keep all rows from the left table

💡 Tip: if you know SQL joins, pd.merge is the same idea in Pandas — on is your join key.

Try it Yourself
Output

          
Ad · responsive