Lesson 25 of 60 · python
Merging and Joining DataFrames
Duration: 20 minutes
Merging & Joining
Combine data from multiple sources with relational operations.
merge (SQL‑like joins)
orders = pd.read_csv('orders.csv')
customers = pd.read_csv('customers.csv')
# Inner join on customer_id
merged = pd.merge(orders, customers, on='customer_id', how='inner')
print(merged.head())
Types of joins
inner: keep only matchesleft: keep all left rowsright: keep all right rowsouter: keep all rows, fill missing with NaN
left_join = pd.merge(df_left, df_right, on='key', how='left')
right_join = pd.merge(df_left, df_right, on='key', how='right')
full_outer = pd.merge(df_left, df_right, on='key', how='outer')
Concatenating vertically or horizontally
# Append rows (vertical)
combined = pd.concat([df1, df2], ignore_index=True)
# Append columns (horizontal)
combined_h = pd.concat([df1, df2], axis=1)
Handling duplicate column names after merge
merged = pd.merge(df1, df2, on='id', suffixes=('_left', '_right'))
pd.merge(df_a, df_b, on='key', how='inner', validate='many_to_one')
```</Alert>