-3

I have a dataframe A:

a 1
a 2
b 1
b 2

Another dataframe B:

a 3
a 4 
b 3

I want my result dataframe to be like

a 1 3
a 1 4 
a 2 3
a 2 4 
b 1 3 
b 2 3 

I wondering how I can get the desired result in python. Thanks a lot!

cs95
  • 274,032
  • 76
  • 480
  • 537
Yingying Chen
  • 31
  • 1
  • 6
  • 2
    Please provide a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) – klutt Jul 12 '17 at 09:25
  • 1
    I'm always wondering whether posting these elementary question is really faster than googling something like `pandas merge` which gives as a second hit a reference to the pandas documentation titled [Merge, join, and concatenate](https://pandas.pydata.org/pandas-docs/stable/merging.html) – Quickbeam2k1 Jul 12 '17 at 10:04

1 Answers1

1

A simple merge using df.merge does this:

df1.merge(df2, on=['A'])

   A  B_x  B_y
0  a    1    3
1  a    1    4
2  a    2    3
3  a    2    4
4  b    1    3
5  b    2    3
cs95
  • 274,032
  • 76
  • 480
  • 537
  • Thank you so much for your reply. I've tried this before and I got a lot more rows than expected. I checked and found that I've a lot of duplicated rows in the result dataframe. I wonder why would I get duplicated rows when applying this method? – Yingying Chen Jul 13 '17 at 05:49
  • @YingyingChen This is _exactly_ what you've specified to be your desired output though! Also, this does not give duplicate rows. It does a natural join on the rows. – cs95 Jul 13 '17 at 08:46