create dataframe from df1 and df2 and take empty value from df2 for column value if not exist in df1 column value

df1 = pd.DataFrame({'call_sign': ['ASD','BSD','CDSF','GFDFD','FHHH'],'frn':['123','124','','656','']})

df2 = pd.DataFrame({'call_sign': ['ASD','CDSF','BSD','GFDFD','FHHH'],'frn':['1234','','124','','765']})

need to get a new df like

df2 = pd.DataFrame({'call_sign': ['ASD','BSD','CDSF','GFDFD','FHHH'],'frn':['123','','124','656','765']})

ie: need to take frn from df2 if it’s missing in df1 and create a new df

>Solution :

Replace empty strings to missing values and use DataFrame.set_index with DataFrame.fillna, because need ordering like df2.call_sign add DataFrame.reindex:

df = (df1.set_index('call_sign').replace('', np.nan)
          .fillna(df2.set_index('call_sign').replace('', np.nan))
  call_sign  frn
0       ASD  123
1      CDSF  NaN
2       BSD  124
3     GFDFD  656
4      FHHH  765

Leave a ReplyCancel reply