Pandas
Merge and Join
Combine frames with merge and concat.
By EZ4Code Team
mergejoinconcat
Code
import pandas as pd
left = pd.DataFrame({"id": [1, 2, 3], "name": ["A", "B", "C"]})
right = pd.DataFrame({"id": [2, 3, 4], "score": [80, 90, 70]})
# Database-style joins on a key
inner = pd.merge(left, right, on="id", how="inner")
left_join = pd.merge(left, right, on="id", how="left")
outer = pd.merge(left, right, on="id", how="outer")
# Different key names
pd.merge(left, right, left_on="id", right_on="id", suffixes=("_l", "_r"))
# Concatenate along rows or columns
a = pd.DataFrame({"x": [1, 2]})
b = pd.DataFrame({"x": [3, 4]})
rows = pd.concat([a, b], ignore_index=True)
cols = pd.concat([a, b], axis=1)
print(inner, left_join, rows)Explanation
merge() performs SQL-style joins keyed on one or more columns, with how controlling inner, outer, left, or right behavior. suffixes disambiguate overlapping non-key columns. concat() stacks frames along either axis, and ignore_index resets the row labels.
More Pandas Snippets
DataFrame Creation
Build DataFrames from dicts, lists, and files.
Indexing and Selecting
Select rows and columns with loc, iloc, and masks.
GroupBy Operations
Split, aggregate, and transform with groupby.
Pivot Tables
Reshape data with pivot, melt, and pivot_table.
Time Series
Resample, shift, and roll windows over time data.
Missing Data
Detect, fill, and drop NaN values.