Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create new dataframe from two dataframes. One df contains column indices the other df the values

I have two dataframes of equal dimensions.

df1 contains column indices.

    left   right   opp 
0    2       0      1
1    2       1      0
2    1       2      0

df2 contains values of interest.

    value1   value2   value3
0    10      25         60
1    30      40         100
2    80      45         30

I want to create a dataframe that takes the column indices from df1, and uses them to grab the values from df2:

    left    right      opp
0    60      10         25
1    100     40         30
2    45      30         80

I was hoping to solve this with applymap and iloc. Something like this:

df3  = df1.applymap(lambda x, y: df2.iloc[x,y]) 

However, applymap only takes in the value of the cell, not the index and value.

I feel this should be a trivial operation, but I'm not seeing it at the moment. I couldn't find a duplicate question either. Any help much appreciated.

like image 493
leermeester Avatar asked Nov 30 '25 02:11

leermeester


1 Answers

It is not that hard but we need help from .values

df=df1.apply(lambda x :df2.values[x.index,x])
   left  right  opp
0    60     10   25
1   100     40   30
2    45     30   80
like image 167
BENY Avatar answered Dec 02 '25 16:12

BENY