0

I have two dataframes

df1 = pd.DataFrame([[1,2],[3,4],[5,6],[7,8]], index = ['a','b','c', 'a'], columns = ['d','e'])
   d  e
a  1  2
b  3  4
c  5  6
a  7  8


df2 = pd.DataFrame([['a', 10],['b',20],['c',30],['f',40]])


   0   1
0  a  10
1  b  20
2  c  30
3  f  40

i want my final dataframe to multiply rows of df1 to multiply by a factor corresponding to value in df2 (for eg. 20 for b)

so my output should look like

     d    e
a   10   20
b   60   80
c  150  180
a   70   80

Kindly provide a solution assuming df1 to be hundreds of rows in length. I could only think of looping through df1.index.

cs95
  • 379,657
  • 97
  • 704
  • 746
stormtrooper12
  • 351
  • 1
  • 3
  • 15

4 Answers4

2

Use set_index and reindex to align df2 with df1 and then mul

In [1150]: df1.mul(df2.set_index(0).reindex(df1.index)[1], axis=0)
Out[1150]:
     d    e
a   10   20
b   60   80
c  150  180
a   70   80
Zero
  • 74,117
  • 18
  • 147
  • 154
1

Create a mapping and call df.apply:

In [1128]: mapping = dict(df2.values)

In [1129]: df1.apply(lambda x: x * mapping[x.name], 1)
Out[1129]: 
     d    e
a   10   20
b   60   80
c  150  180
a   70   80
cs95
  • 379,657
  • 97
  • 704
  • 746
0

IIUC:

In [55]: df1 * pd.DataFrame(np.tile(df2[[1]],2), columns=df1.columns, index=df2[0])
Out[55]:
     d    e
a   10   20
a   70   80
b   60   80
c  150  180

Helper DF:

In [57]: pd.DataFrame(np.tile(df2[[1]],2), columns=df1.columns, index=df2[0])
Out[57]:
    d   e
0
a  10  10
b  20  20
c  30  30
MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419
0

This is straight forward. You just make sure they have a common axis, then you can combine them:

put the lookup column into the index

df2.set_index(0, inplace=True)

    1
0   
a   10
b   20
c   30

Now you can put that column into df1 very easily:

df1['multiplying_factor'] = df2[1]

Now you just want to multiply two columns:

df1['final_value'] = df1.e*df1.multiplying_factor

Now df1 looks like:

    d   e   multiplying_factor  final_value
a   1   2   10                  20
b   3   4   20                  80
c   5   6   30                  180
a   7   8   10                  80
greg_data
  • 2,247
  • 13
  • 20