Example for pandas Merge

Here’s an example for the merge capabilities of pandas, which allow the user to work with DataFrames just like in SQL.

import pandas as pd
dfA = pd.DataFrame({'A': ['A0','A1','A2','A3'], 'Key': ['K0','K1','K2','K4']})
dfB = pd.DataFrame({'B': ['B0','B1','B2','B3'], 'Key': ['K0','K1','K2','K5']})
dfInner = dfA.merge(dfB,how='inner',left_on='Key',right_on='Key')
print('Inner:\n', dfInner, '\n')
dfLeft = dfA.merge(dfB,how='left',left_on='Key',right_on='Key')
print('Left:\n', dfLeft, '\n')
dfRight = dfA.merge(dfB,how='right',left_on='Key',right_on='Key')
print('Right:\n', dfRight, '\n')
dfOuter = dfA.merge(dfB,how='outer',left_on='Key',right_on='Key')
print('Outer:\n', dfOuter, '\n')


Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website