Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

Assume, I have the below two data frames

Example 1:

sku loc flag  

122  61 True 

123  61 True

113  62 True 

122  62 True 

123  62 False

122  63 False

301  63 True 

Example 2:

sku dept 

113 a

122 b

123 b

301 c

Now, using pandas I would like to perform the merge and join operation, to create the following data frame

Example3

sku loc flag   dept  

122  61 True   b

123  61 True   b

113  62 True   a

122  62 True   b

123  62 False  b

122  63 False  b

301  63 True   c

Both 

df_Example1.join(df_Example2,lsuffix='_ProdHier')

df_Example1.join(df_Example2,how='outer',lsuffix='_ProdHier')

It's not working. Can anyone tell me where I went wrong?

1 Answer

0 votes
by (26.4k points)

Now perform a left merge, this will ultimately use sku column as column to join on:

In [26]:

df.merge(df1, on='sku', how='left')

Out[26]:

   sku  loc   flag dept

0  122   61   True    b

1  122   62   True    b

2  122   63  False    b

3  123   61   True    b

4  123   62  False    b

5  113   62   True    a

6  301   63   True    c

In case, if sku in you index, then do:

In [28]:

df.merge(df1, left_index=True, right_index=True, how='left')

Out[28]:

     loc   flag dept

sku                 

113   62   True    a

122   61   True    b

122   62   True    b

122   63  False    b

123   61   True    b

123   62  False    b

301   63   True    c

You can also use "map", in the event that you set sku as the index on your second df, so essentially it turns into a Series then the code streamlines to this:

In [19]:

df['dept']=df.sku.map(df1.dept)

df

Out[19]:

   sku  loc   flag dept

0  122   61   True    b

1  123   61   True    b

2  113   62   True    a

3  122   62   True    b

4  123   62  False    b

5  122   63  False    b

6  301   63   True    c

Want to learn more concepts related to python? Join python course fast!

For more details, do check out our video tutorial...

Related questions

0 votes
1 answer
asked Jul 22, 2019 in BI by Vaibhav Ameta (17.6k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...