0

I have two dataframes A and B which is of the following type

A:
col1    col2    
abc     Pid1     
cdz     Pid1

B:
col2    value
Pid1    2
Pid1    3
Pid1    4

Desired Output:
col1   col2   value
abc    Pid1   2
abc    Pid1   3
abc    Pid1   4
cdz    Pid1   2
cdz    Pid1   3
cdz    Pid1   4

I have tried merge(outer join) but didnt get the desired result

Please advice

Thank you in advance

python_interest
  • 874
  • 1
  • 9
  • 27
  • 1
    Use `A.merge(B)` – Space Impact Jul 30 '19 at 09:05
  • 2
    Possible duplicate of [Pandas Merging 101](https://stackoverflow.com/questions/53645882/pandas-merging-101) – Space Impact Jul 30 '19 at 09:06
  • 1
    possible duplicate of https://stackoverflow.com/questions/34161978/pandas-two-dataframe-cross-join?lq=1 – Ayoub ZAROU Jul 30 '19 at 09:17
  • 2
    unless I don't understand merges, but an outer merge on col2 should give you your required output.`pd.merge(df,df2,on='col2',how='outer')` works for me on your sample dataset. – Umar.H Jul 30 '19 at 09:17
  • 1
    "I have tried merge(outer join) but didnt get the desired result" please add your code so we can see where you went wrong. `merge` is certainly the right answer. – Dan Jul 30 '19 at 09:25
  • I will add it. I guess I am making some mistake. Theoritically, outer join should include everything – python_interest Jul 30 '19 at 09:41
  • Thank you for taking time to answer. My bad I made a careless mistake while generating a column used for merging. Thank you guys anyway – python_interest Jul 31 '19 at 02:24

1 Answers1

2

Simple Outer Merging:

A = pd.DataFrame({'col1':['abc', 'cdz'], 'col2':['Pid1', 'Pid1']})

print(A)
    col1 col2
0   abc  Pid1
1   cdz  Pid1
B = pd.DataFrame({'col2':['Pid1', 'Pid1','Pid1'], 'value':['2','3','4']})

print(B)

    col2  value
0   Pid1    2
1   Pid1    3
2   Pid1    4
C = A.merge(B, on='col2', how = 'outer', indicator = True)

print(C)

    col1 col2 value _merge
0   abc  Pid1   2    both
1   abc  Pid1   3    both
2   abc  Pid1   4    both
3   cdz  Pid1   2    both
4   cdz  Pid1   3    both
5   cdz  Pid1   4    both
AmmarYasir
  • 92
  • 9