python - How to use merge in pandas -


sorry guys, know basic question, i'm beginner

in [55]: df1 out[55]:    x  y  1  3 b  2  4 c  3  5 d  4  6 e  5  7  in [56]: df2 out[56]:    y  z b  1  9 c  3  8 d  5  7 e  7  6 f  9  5 

pd.merge(df1, df2) gives:

in [56]: df2 out[56]:    x  y  z  0  1  3  8 1  3  5  7 2  5  7  6 

i'm confused use of merge, '0','1','2' mean? example,when index 0, why x 1, y 3 , z 8?

you due defaults pd.merge:

merge(left, right, how='inner', on=none, left_on=none, right_on=none, left_index=false, right_index=false, sort=false, suffixes=('_x', '_y'), copy=true, indicator=false)  on : label or list     field names join on. must found in both dataframes. if on     none , not merging on indexes, merges on intersection of     columns default. 

you haven't pass key on key, merges on intersection of columns default. have different indices df1 , df2 if want keep left or right should specify that:

in [43]: pd.merge(df1, df2) out[43]:    x  y  z 0  1  3  8 1  3  5  7 2  5  7  6  in [44]: pd.merge(df1, df2, on='y', left_index=true) out[44]:    x  y  z c  1  3  8 d  3  5  7 e  5  7  6  in [45]: pd.merge(df1, df2, on='y', right_index=true) out[45]:    x  y  z  1  3  8 c  3  5  7 e  5  7  6 

Comments