user2237511
user2237511

Reputation: 1149

How do I multiply all elements of a column of a dataframe with value specified for that column in another dataframe?

My question is quite similar to Multiply two pandas DataFrames based on column and Multiply two data frames with similar index in python pandas but a little different. I tried both the suggestions but it didn't work for me.

All my inputs are read from a csv file.

Input 1

   Attr1   Attr2
0     10      20
1     30      40

Assume Input 2 specifies weights for Attr1 and Attr2

Input 2

   Attr1   Attr2
0     5        6

My output would be multiplying the weights from Input 2 to every row of that corresponding attribute in Input 1 so my output needs to be

   Attr1   Attr2
0     50     120
1    150     240

Upvotes: 1

Views: 1678

Answers (2)

jezrael
jezrael

Reputation: 863741

You can first select first row in d2 - output is Series and then multiple by mul:

print (d2.iloc[0])
Attr1    5
Attr2    6
Name: 0, dtype: int64

d = d1.mul(d2.iloc[0])
print (d)
   Attr1  Attr2
0     50    120
1    150    240

Upvotes: 4

alexey
alexey

Reputation: 706

Here a possible solution:

import pandas as pd


d1 = pd.DataFrame([[10, 20], [30, 40]], columns=['Attr1', 'Attr2'])
d2 = pd.DataFrame([[5, 6]], columns=['Attr1', 'Attr2'])

# iterate over columns of the second dataframe
for col in d2.columns: 
    # you can check whether col is in d1 
    # if col in d1.columns:
    d1[col] = d1[col] * d2[col][0]

Upvotes: 1

Related Questions