We can use how='left'
tells merge() to left merge two dataframes. The following is the Pandas syntax, in which df_1 and df_2 are two dataframes to be merged.
df_1.merge(df_2, how=’left’, left_index=True, right_index=True)
Step 1: Prepare the data to be left merged
The following is the two dataframes to be left merged.
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
Step 2: Use merge() to left merge two dataframes
Use how='left'
in merge()
to left merge 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