0

Using pandas, how can I find the position of rows of one dataframe in another dataframe?

Example:

We have a dataframe df_A

import pandas as pd
df_A = pd.DataFrame([[1, 2,3], [1, 3,4], [1, 4,9]], columns=['idx_1', 'idx_2','values'])

and another dataframe df_B

df_B = pd.DataFrame([[1, 2], [1, 4]], columns=['idx_1', 'idx_2'])

I want to the correspondence between the idx-columns of df_A to the idx-columns of df_B:

     idx_1  idx_2  values row_B
0      1      2      3     0
1      1      3      4     NAN
2      1      4      9     1

1 Answers1

0

Use DataFrame.merge with left join and DataFrame.reset_index and rename for avoid losing index of df_B:

df2 = df_B.reset_index().rename(columns={'index':'row_B'})
df = df_A.merge(df2, how='left', on=['idx_1', 'idx_2'])
print (df)
   idx_1  idx_2  values  row_B
0      1      2       3    0.0
1      1      3       4    NaN
2      1      4       9    1.0
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252