1

I have two dataframes like the following:

df1:
   dp  value
0  d1      2
1  d1      3
2  d2      7
3  d2      8
4  d3      6

df2:
  fv_name  dp  value
0     x-1  d1      2
1     x-2  d1      2
2     x-3  d1      3
3     x-1  d2      7
4     x-2  d2      7
5     x-3  d2      8
6     x-1  d3      6
7     x-2  d3      6
8     x-3  d3      6

And I am trying to add the indices from df1 onto df2 to produce a dataframe that looks like the following:

df3:
  fv_name  dp  value   dp_id
0     x-1  d1      2    0
1     x-2  d1      2    0
2     x-3  d1      3    1
3     x-1  d2      7    2
4     x-2  d2      7    2
5     x-3  d2      8    3
6     x-1  d3      6    4
7     x-2  d3      6    4
8     x-3  d3      6    4

I was attempting some different types of merges like the following, but I am unable to achieve my desired dataframe.

df3 = pd.merge(df1, df2, on=['dp', 'value'], how='outer')

Thanks in advance for any help with this.

DJK
  • 8,924
  • 4
  • 24
  • 40
bwrabbit
  • 529
  • 1
  • 4
  • 25

2 Answers2

2

Promote the index of d1 to a column, then perform the merge:

df1['dp_id'] = df1.index
df3 = pd.merge(df1, df2, on=['dp', 'value'], how='outer')
jpp
  • 159,742
  • 34
  • 281
  • 339
0

Using rename_axis & reset_index

df3 = pd.merge(df1.rename_axis('dp_id').reset_index(), df2,  
                                           on=['dp', 'value'], how='outer')
DJK
  • 8,924
  • 4
  • 24
  • 40