User Tools

Site Tools


merging_on_swapping_keys_-_not_for_idiots

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

merging_on_swapping_keys_-_not_for_idiots [2016/10/12 08:50] (current)
vincenzo created
Line 1: Line 1:
 +<code python>
 +import pandas as pd
 +import re
 +
 +df1 = pd.DataFrame({'​Banner':​ {0: '​banner1',​ 1: '​banner2',​ 2: '​banner3'​},​
 +                    '​Campaign':​ {0: '​campaign1',​ 1: '​campaign2',​ 2: '​12345'​},​
 +                    '​Country ': {0: '​de',​ 1: '​it',​ 2: '​de'​},​
 +                    '​Date':​ {0: '​1/​1/​2016',​ 1: '​2/​1/​2016',​ 2: '​1/​1/​2016'​},​
 +                    '​Value_1':​ {0: 10, 1: 5, 2: 20}})
 +
 +df2 = pd.DataFrame({'​Banner':​ {0: '​banner1',​ 1: '​banner2',​ 2: '​banner3',​ 3: '​banner4',​ 4: '​banner5'​},​
 +                    '​Campaign':​ {0: '​campaign1',​1:​ '​campaign2',​ 2: '​none',​3:​ '​campaign4',​4:​ '​campaign5'​},​
 +                    '​Country ': {0: '​de',​ 1: '​it',​ 2: '​de',​ 3: '​en',​ 4: '​en'​},​
 +                    '​Date':​ {0: '​1/​1/​2016',​ 1: '​2/​1/​2016',​ 2: '​1/​1/​2016',​ 3: '​3/​1/​2016',​ 4: '​4/​1/​2016'​},​
 +                    '​Value_2':​ {0: 5, 1: 10, 2: 15, 3: 20, 4: 25},              ​
 +                    '​id_campaign':​ {0: '​none',​ 1: '​none',​ 2: '​12345',​ 3: '​none',​ 4: '​none'​}})
 +
 +df3 = pd.merge(df2,​ df1, on=['​Date','​Campaign','​Banner'​],​ how='​left'​)
 +df4 = pd.merge(df2,​ df1, on=['​Date','​Banner'​],​ how='​left'​)
 +df3['​Value_1'​] = df3['​Value_1'​].combine_first(df4['​Value_1'​]).fillna(0).astype(int)
 +df = df3.drop('​Country _y', axis=1)
 +df = df.rename(columns = {'​Country _x':'​Country'​})
 +</​code>​
 +
  
merging_on_swapping_keys_-_not_for_idiots.txt ยท Last modified: 2016/10/12 08:50 by vincenzo