join() is essentially a convenience wrapper around merge() specifically optimized for the common case of combining DataFrames by their index rather than by an arbitrary column, defaulting to how='left', unlike merge()'s default of 'inner', which keeps every row of the calling DataFrame and fills in NaN for any unmatched rows from the other one. Passing the on parameter lets you join on a regular column of the calling DataFrame against the other DataFrame's index instead of index-to-index, a common pattern for attaching lookup data.
1Understanding df.join()
join() is essentially a convenience wrapper around merge() specifically optimized for the common case of combining DataFrames by their index rather than by an arbitrary column, defaulting to how='left', unlike merge()'s default of 'inner', which keeps every row of the calling DataFrame and fills in NaN for any unmatched rows from the other one. Passing the on parameter lets you join on a regular column of the calling DataFrame against the other DataFrame's index instead of index-to-index, a common pattern for attaching lookup data.
join() defaults to how='left' and joins on the index, while merge() defaults to how='inner' and joins on columns by default — remember these different defaults, since assuming one function's behavior for the other is an easy mistake.
import pandas as pd
df1 = pd.DataFrame({"name": ["Alice", "Bob"]}, index=[1, 2])
df2 = pd.DataFrame({"score": [90, 85]}, index=[1, 2])
print(df1.join(df2))2Practical Example
Here is a real-world application of df.join() showing how it is used in production Pandas code.
import pandas as pd
orders = pd.DataFrame({"customer_id": [1, 2, 3], "total": [50, 30, 20]})
customers = pd.DataFrame({"name": ["Alice", "Bob"]}, index=[1, 2])
print(orders.join(customers, on="customer_id"))3Best Practices
Follow these guidelines when working with df.join():
1. Use join() specifically for the common case of combining DataFrames by their index, since it's more concise than the equivalent merge() call
2. Use merge() instead of join() when combining on regular columns rather than the index, since that's what merge() is more naturally suited for
3. Set an appropriate index before using join(), if the DataFrames aren't already indexed by the key you want to combine on
Tip: join() defaults to how='left' and joins on the index, while merge() defaults to how='inner' and joins on columns by default — remember these different defaults, since assuming one function's behavior for the other is an easy mistake.
import pandas as pd
df1 = pd.DataFrame({"name": ["Alice", "Bob"]}, index=[1, 2])
df2 = pd.DataFrame({"score": [90, 85]}, index=[1, 2])
print(df1.join(df2))