0

I have two dataframes df1 and df2.

df1
index     emp_id     name         code 
  0          07       emp07        'A'      
  1          11       emp11        'B'      
  2          30       emp30        'C'  

df2
index       emp_id   salary 
     0      06       1000            
     1      17       2000             
     2      11       3000

I want to store a map from df1['emp_id'] to df2.index.

Example: input array - ['emp11','B'] (from df1)

Expected output: [11, 2] # this is df1['emp_id'], df2.index

Code I am trying:

columns_to_idx = {emp_id: i for i, emp_id in 
    enumerate(list(DF1.set_index('emp_id').loc[DF2.index][['name', 'code']]))}
smci
  • 32,567
  • 20
  • 113
  • 146
androidraj
  • 85
  • 2
  • 7
  • Related: [Pandas Merging 101](https://stackoverflow.com/questions/53645882/pandas-merging-101) – smci Mar 16 '20 at 06:33

1 Answers1

4

I think you need DataFrame.merge with inner join and DataFrame.reset_index for column from index for avoid lost it:

df = df1.merge(df2.reset_index(), on='emp_id')
print (df)
   emp_id   name code  index  salary
0      11  emp11   B      2    3000

Then is possible create MultiIndex and select by tuple:

df2 = (df1.merge(df2.reset_index(), on='emp_id')
         .set_index(['name','code'])[['emp_id','index']])
print (df2)
            emp_id  index
name  code               
emp11 B         11      2

print (df2.loc[('emp11','B')].tolist())
[11, 2]
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • 2
    It helps to explain to the OP why `merge` does what they need, and why not the other pandas commands. Related: [Pandas Merging 101](https://stackoverflow.com/questions/53645882/pandas-merging-101) – smci Mar 16 '20 at 06:31