How do I merge two pandas DataFrames, and which join type should I use?
par Équipe NextData
I need to combine two pandas DataFrames on a common column, like a SQL join. I am not sure which how option to use, and after merging I sometimes end up with more rows than I started with.
Signaler
1 réponse
Use merge, and choose how according to which rows must survive.
import pandas as pd
result = customers.merge(orders, on="customer_id", how="left")
how |
Rows kept |
|---|---|
"inner" (default) |
Only keys present in both |
"left" |
All rows of the left frame |
"right" |
All rows of the right frame |
"outer" |
All rows of both |
Common variations:
# key columns named differently
customers.merge(orders, left_on="id", right_on="customer_id")
# several key columns
a.merge(b, on=["country", "year"])
# join on the index
a.merge(b, left_index=True, right_index=True)
# same column names on both sides
a.merge(b, on="id", suffixes=("_crm", "_erp"))
Why the row count grows: if a key appears several times on both sides, every combination is produced. Make pandas check your assumption:
customers.merge(orders, on="customer_id", how="left", validate="one_to_many")
validate raises an error if the keys are not unique where you said they would be.
To see where each row came from, add indicator=True: a _merge column shows both, left_only or right_only. It is the quickest way to find rows with no match.
Check that the key columns have the same type on both sides. With an integer key against a text key, pandas raises a ValueError: convert one side first, for example orders["customer_id"].astype(int). If both keys are text but formatted differently ("007" against "7", a trailing space), there is no error and nothing matches.
Use pd.concat instead when you want to stack frames with the same columns on top of each other.
Réponse rédigée par l'équipe NextData et relue par un expert.
