Arron
Arron

Reputation: 91

How do I join two tables even if some rows are missing from each other

**Table 1**                      **Table2** 
Column_name   Value          Column_name   Value
K1            13              K1            65
K2            25              K2            31
K4            46              K3            71
H1            56              H2            56
H3            26
H4            46
H6            56

I want to merge tables whilst having the same column name. The inner join below only search for common columns name with Table 1 as reference.

left_join = pd.merge(table1, table2, 
                       on = 'column_name',
                       how = 'left')

I want my output to be:

Column_name   Value1      Value2
K1            13          65
K2            25          31
K3                        71
K4            46          
H1            56          
H2                        56
H3            26
H4            46
H6            56

Upvotes: 1

Views: 170

Answers (1)

LMKR
LMKR

Reputation: 647

Use outer join from the pandas.

>>> df1 = pd.DataFrame({"Column_name":["K1","K2","K4","H1","H3","H4","H6"],"col2":[13,25,46,56,26,46,56]})
>>> df2 = pd.DataFrame({"Column_name":["K1","K2","K3","H2"],"col3":[65,31,71,56]})
>>> pd.merge(df1, df2, on="Column_name", how="outer")
  Column_name  col2  col3
0          K1  13.0  65.0
1          K2  25.0  31.0
2          K4  46.0   NaN
3          H1  56.0   NaN
4          H3  26.0   NaN
5          H4  46.0   NaN
6          H6  56.0   NaN
7          K3   NaN  71.0
8          H2   NaN  56.0
>>>

Upvotes: 3

Related Questions