Python para Data Science e Analytics
Python para Data Science e Analytics › Guides › How to Merge DataFrames in pandas: A Guide with Examples

How to Merge DataFrames in pandas: A Guide with Examples

To merge DataFrames in pandas, call `pd.merge(left_df, right_df, on='key', how='inner')`. The `how` parameter selects the join type, and `on`—or `left_on` and `right_on`—sets the key column. After the merge, check row counts and use `indicator=True` to see which rows came from each table.

Topics: pandas, merge, dataframe

How does a pandas merge work in practice?

A pandas merge combines two tables through one or more shared columns. The tables need a compatible key, and the result contains columns from both sides, with suffixes added when names repeat. The merge does not change the original DataFrames; it returns a new DataFrame.

A minimal example: `customers` has `customer_id` and `city`; `orders` has `customer_id` and `amount`. Running `pd.merge(customers, orders, on='customer_id', how='left')` keeps every customer and adds matching orders. Customers without orders get `NaN` in the order columns.

Store the result in a variable and compare `df1.shape`, `df2.shape`, and `result.shape`. Use `result.head()` to inspect the first rows and `result.columns` to see whether suffixes were applied.

Which join type should you use: inner, left, right, or outer?

The `how` parameter controls which keys enter the result. If you want only matches, use `inner`; if the left table is the base, use `left`; if the right table is the base, use `right`; if you want to audit both sides, use `outer`.

With `left`, rows from the left table without a match get `NaN` in the right-side columns. With `outer`, keys exclusive to either side appear, which helps diagnose records that do not match. Before choosing, define which table is the base of the analysis and what cardinality you expect.

How do you choose the key, use multiple columns, and merge on the index?

The key must exist in both tables with the same meaning. Different names? Use `left_on='customer_id'` and `right_on='client_id'`. Multiple columns? Pass a list: `on=['customer_id', 'order_date']`.

Check the key data type with `df['customer_id'].dtype`. If one side stores text and the other stores numbers, convert explicitly with `astype` before the merge. For text keys, also check spaces, accents, and letter case.

When both tables have columns with the same name, `suffixes=('_left', '_right')` keeps the result readable. To use the index, replace `on` with `left_index=True` and `right_index=True`. If one side uses the index and the other uses a column, combine `left_index=True` with `right_on='key'`.

How do you check for duplicate or lost rows after a merge?

Use `indicator=True` to create the `_merge` column, with values `both`, `left_only`, and `right_only`. `result['_merge'].value_counts()` shows how many rows came from each side. To list what stayed only on the left, filter `result[result['_merge'] == 'left_only']`.

Duplicate keys can multiply rows. Before the merge, run `df['key'].duplicated().sum()` and `df['key'].is_unique`. If the key is not unique, the merge may produce more rows than the original table; that is not always an error, but it must be intentional.

The `validate` parameter helps declare the expected cardinality: `validate='one_to_one'`, `'one_to_many'`, `'many_to_one'`, or `'many_to_many'`. If the actual relationship does not match the declaration, pandas raises an error instead of returning a silently wrong table.

Where can you practice merge, cleaning, and data analysis in Python?

The Python for Data Science and Analytics course, from zero to advanced, covers Pandas, NumPy, user-defined functions, loops and conditionals, data visualization, data cleaning and preparation, and outlier detection. The machine learning part includes linear and logistic regression, K-Means, SVM, Naive Bayes, decision trees, Random Forest, Gradient Boosting, XGBoost, LightGBM, feature selection, and cross-validation.

The course has three main modules—Basic, Intermediate, and Advanced—plus bonus modules. Lessons are recorded in high quality and watched at the student's pace. It includes real market projects for a portfolio, guided practice exercises, unlimited access with no expiration date, a completion certificate, and an exclusive community for networking. It ends with a final project: end-to-end exploratory analysis and machine learning. No prior programming knowledge is required to start.

The listed price is R$ 470, with a credit-card option of 12 installments of R$ 20.37, paid through Hotmart checkout; boleto is also listed as a payment option. You can see the course at https://python.paanalytics.net/.

Join type (`how`)Rows in the resultTypical useWhat to check
`inner`Only keys present in both tablesJoining records that must matchRows dropped from either side
`left`All rows from the left table, plus matchesLeft table is the base`NaN` in right-side columns
`right`All rows from the right table, plus matchesRight table is the base`NaN` in left-side columns
`outer`All keys from both tablesAuditing mismatches across tablesLarger result and more `NaN` values

Based on how pandas defines the `how` parameter for `pd.merge`; the table describes join behavior, not product data.

Practice merge in the pandas module

Secure payment via Hotmart, up to 12 installments.

Enroll now Product site

Frequently asked questions

Can I merge DataFrames when the key columns have different names?

Yes. Use `left_on='customer_id'` and `right_on='client_id'`. The result keeps both key columns unless you drop one. Check that both columns store the same type of value before merging.

What happens if the key has duplicate values?

A merge matches every occurrence, so duplicate keys can multiply rows. Use `df['key'].duplicated().sum()` and `is_unique` before merging, and set `validate` to the cardinality you expect. If the row count grows, inspect the duplicates rather than assuming the merge failed.

How do I find rows that did not match?

Set `indicator=True` and inspect the `_merge` column. Filter `left_only` or `right_only`, or run an `outer` merge to keep keys from both tables. Then decide whether to drop, fix, or keep those rows.

Is `merge` better than `join` in pandas?

They solve related tasks. `pd.merge` is the general table-join function with explicit keys and join types. `DataFrame.join` is a convenience method that often uses the index. Use the one that makes the key and join type clearest for your case.

Can I merge more than two DataFrames?

Yes. Merge them in sequence, checking the key and row count after each step. Keep the intermediate result in a named variable, and use `validate` or `indicator` at each join so an early mismatch does not spread through the final table.

Ler em português →