Introduction
An outer join helps combine two tables so you keep all data from both, even if some parts don't match.
An outer join helps combine two tables so you keep all data from both, even if some parts don't match.
pd.merge(left_df, right_df, how='outer', on='key_column')
left_df and right_df are the two tables (dataframes) you want to join.
how='outer' means keep all rows from both tables.
pd.merge(df1, df2, how='outer', on='id')
pd.merge(df1, df2, how='outer', left_on='emp_id', right_on='id')
pd.merge(df1, df2, how='outer')This example joins two tables on the 'id' column. It keeps all rows from both tables. Missing values are shown as NaN.
import pandas as pd # Create first dataframe df1 = pd.DataFrame({ 'id': [1, 2, 3], 'name': ['Alice', 'Bob', 'Charlie'] }) # Create second dataframe df2 = pd.DataFrame({ 'id': [2, 3, 4], 'age': [30, 25, 40] }) # Outer join on 'id' result = pd.merge(df1, df2, how='outer', on='id') print(result)
Missing values appear as NaN after an outer join.
Outer join is useful to find unmatched rows in either table.
Outer join keeps all rows from both tables.
Missing data is filled with NaN.
Use how='outer' in pd.merge() to do an outer join.
df1 = pd.DataFrame({'key': ['A', 'B'], 'val1': [1, 2]})
df2 = pd.DataFrame({'key': ['B', 'C'], 'val2': [3, 4]})pd.merge(df1, df2, on='key', how='outer')?pd.merge(df1, df2, how='outer', on='key', left_index=True)
df1 = pd.DataFrame({'id': [1, 2, 3], 'score': [10, 20, 30]})
df2 = pd.DataFrame({'id': [2, 3, 4], 'grade': ['B', 'A', 'C']})Pass the test and this pattern moves unknown