Introduction
There are two methods to left join two dataframes in Pandas.
Method 1
We can use how='left'
tells join() to left join two dataframes.
df_1.join(df_2, how=’left’)
Method 2
We can use how='left'
tells merge() to left join two dataframes.
df_1.merge(df_2, how=’left’, left_index=True,right_index=True)
Sample Data
The following is the two dataframes to be left joined.
import pandas as pd
# dataframe 1
df_1 = pd.DataFrame({'Brand': ['Tesla', 'Toyota','Tesla','Ford'],
'Location': ['CA', 'CA','NY','MA']},index=list('abcd'))
print("df_1: \n",df_1)
# dataframe 2
df_2 = pd.DataFrame({
'Name': ['Jake', 'Jacob','John','Jess','James']},index=list('abdek'))
print("df_2 \n",df_2)
df_1: Brand Location a Tesla CA b Toyota CA c Tesla NY d Ford MA df_2 Name a Jake b Jacob d John e Jess k James
Method 1: Use join()
Use how='left'
in join()
to left join two dataframes.
# use how='left' in join() to left join two dataframes
joined_dataframe=df_1.join(df_2,how='left')
print(joined_dataframe)
Brand Location Name a Tesla CA Jake b Toyota CA Jacob c Tesla NY NaN d Ford MA John
Method 2: Use merge()
Use how='left'
in merge()
to left join two dataframes.
# use how='left' in merge() to left join two dataframes
joined_dataframe=df_1.merge(df_2, how='left', left_index=True,right_index=True)
print(joined_dataframe)
Brand Location Name a Tesla CA Jake b Toyota CA Jacob c Tesla NY NaN d Ford MA John