How do I combine two dataframes?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
In pandas, "combine two dataframes" can mean several different operations. The right tool depends on whether you want to stack rows, line up columns by index, or join records based on a shared key.
Use concat when the tables already have the same shape
pd.concat is the simplest option when the two dataframes already represent the same kind of data and you just want to append them.
That produces one longer dataframe. ignore_index=True is usually helpful because it creates a clean sequential index instead of preserving duplicate row labels.
You can also concatenate horizontally:
This aligns rows by index rather than by a named column.
Use merge when you have a join key
If both dataframes share a column such as customer_id, use merge. This is the pandas equivalent of a SQL join.
The how argument controls the join type:
- '
innerkeeps only matching keys.' - '
leftkeeps every row from the left dataframe.' - '
rightkeeps every row from the right dataframe.' - '
outerkeeps all keys from both sides.'
If the key names differ, use left_on= and right_on=:
Use join when the index is the key
DataFrame.join is convenient when the relationship is already represented by the index:
This is effectively an index-based merge and can be very readable when your data is already indexed correctly.
Choosing the right operation
A good rule of thumb is:
- Use
concatto stack or align whole tables. - Use
mergeto join by one or more columns. - Use
joinwhen the index already represents the relationship.
If the wrong method still appears to "work," inspect the output carefully. Pandas will happily align on indices or keys in ways that may not match your intent.
Common Pitfalls
The most common problem is accidental many-to-many joins. If both dataframes contain repeated values in the join column, merge creates every combination of those matches, which can multiply the row count unexpectedly.
Another issue is mismatched data types. A key column of integers in one dataframe and strings in the other will not join correctly even if the values look the same to a human reader.
concat(axis=1) is also easy to misuse. It aligns by index, not by row position after sorting or filtering, so two dataframes with different indices may produce unexpected NaN values.
Finally, check for duplicate column names. merge adds suffixes such as _x and _y when names overlap, which is a sign you may need to rename columns before joining.
Summary
- Use
pd.concatto append rows or line up whole dataframes by index. - Use
DataFrame.mergefor SQL-style joins on shared columns. - Use
DataFrame.joinwhen the join key is already the index. - Match key data types before joining and inspect the row count afterward.
- If the result looks odd, check the join type, key uniqueness, and index alignment first.

