6. Implementation of dataframe merging using python.

import pandas as pd

left = pd.DataFrame({

   'id':[1,2,3,4,5],

   'Name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'],

   'subject_id':['sub1','sub2','sub4','sub6','sub5']})

right = pd.DataFrame(

   {'id':[1,2,3,4,5],

   'Name': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty'],

   'subject_id':['sub2','sub4','sub3','sub6','sub5']})

print (left)

print (right )

#Merge Two DataFrames on a Key

import pandas as pd

left = pd.DataFrame({

   'id':[1,2,3,4,5],

   'Name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'],

   'subject_id':['sub1','sub2','sub4','sub6','sub5']})

right = pd.DataFrame({

'id':[1,2,3,4,5],

   'Name': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty'],

   'subject_id':['sub2','sub4','sub3','sub6','sub5']})

print (pd.merge(left,right,on='id'))

#Merge Two DataFrames on Multiple Keys

import pandas as pd

left = pd.DataFrame({

   'id':[1,2,3,4,5],

   'Name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'],

   'subject_id':['sub1','sub2','sub4','sub6','sub5']})

right = pd.DataFrame({

'id':[1,2,3,4,5],

   'Name': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty'],

   'subject_id':['sub2','sub4','sub3','sub6','sub5']})

print (pd.merge(left,right,on=['id','subject_id']) )

#Left Join

import pandas as pd

left = pd.DataFrame({

   'id':[1,2,3,4,5],

   'Name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'],

   'subject_id':['sub1','sub2','sub4','sub6','sub5']})

right = pd.DataFrame({

   'id':[1,2,3,4,5],

   'Name': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty'],

   'subject_id':['sub2','sub4','sub3','sub6','sub5']})

print (pd.merge(left, right, on='subject_id', how='left') )

#Right Join

import pandas as pd

left = pd.DataFrame({

   'id':[1,2,3,4,5],

   'Name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'],

   'subject_id':['sub1','sub2','sub4','sub6','sub5']})

right = pd.DataFrame({

   'id':[1,2,3,4,5],

   'Name': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty'],

   'subject_id':['sub2','sub4','sub3','sub6','sub5']})

print (pd.merge(left, right, on='subject_id', how='right') )

#Outer Join

import pandas as pd

left = pd.DataFrame({

   'id':[1,2,3,4,5],

   'Name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'],

   'subject_id':['sub1','sub2','sub4','sub6','sub5']})

right = pd.DataFrame({

   'id':[1,2,3,4,5],

   'Name': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty'],

   'subject_id':['sub2','sub4','sub3','sub6','sub5']})

print (pd.merge(left, right, how='outer', on='subject_id'))

#Inner Join

import pandas as pd

left = pd.DataFrame({

   'id':[1,2,3,4,5],

   'Name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'],

   'subject_id':['sub1','sub2','sub4','sub6','sub5']})

right = pd.DataFrame({

   'id':[1,2,3,4,5],

   'Name': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty'],

   'subject_id':['sub2','sub4','sub3','sub6','sub5']})

print (pd.merge(left, right, on='subject_id', how='inner'))

Post a Comment

0 Comments