0

I have two dataframes.

df1:

Name Place Price
0 John NY 0
1 Alex London 10
2 Bob Sydney 20
3 Will Munich 15
4 Alex London 10

df2:

Name Place Price
0 John NY 0
1 Alex London 10
2 Tim HK 6

I want an output as follows: df2:

Name Place Price Index
0 John NY 0 [0]
1 Alex London 10 [1,4]
2 Tim HK 6 Empty list

I tried:

index_list = []
for row in df2.rows: 
  i = df1[(df1['Name'] == row['Name']) & (df1['Place'] == row['Place']) & (df1['Price'] == row['Price']].index
  index_list.append(i.to_list()) 
df2['Index'] = index_list

Is there an efficient (and elegant) way to do this?

Vineet
  • 33
  • 4

1 Answers1

0

Not sure if this is what you have in mind; a merge, coupled with a groupby works:

grouper = [*df_2.columns]
(df_1.reset_index()
     .merge(df_2, on = grouper)
     .groupby(grouper, sort = False, as_index = False)
     .index
     .agg(list)
  )

   Name   Place  Price   index
0  John      NY      0     [0]
1  Alex  London     10  [1, 4]
sammywemmy
  • 27,093
  • 4
  • 17
  • 31