Dario Bani
Dario Bani

Reputation: 123

Multiplying Dataframes in Python (same index)

I'm trying to multiply 2 dataframes (herebelow)

df1

enter image description here

df2

enter image description here

and I'm expecting something like this as a result:

enter image description here

I found a way to do it with numpy but I lose my index and column values.

Thanks for your help in advance.

Upvotes: 0

Views: 1198

Answers (2)

nick
nick

Reputation: 1340

You should use mul and set the axis to "rows":

df1 = pd.DataFrame({"0": [1,2,3], "1": [2,4,6], "2": [3,6,9]})
df2 = pd.DataFrame({"weights": [.1,.2,.3]})

df1.mul(df2.weights, axis="rows")

Upvotes: 1

Melkozaur
Melkozaur

Reputation: 136

You can multiply data-frame columns element wise directly:

for i in df1.columns:
   df1[i] *= df2['Weights']

It will keep index and column names of df1 and assign the good values as you wish.

Also, you can create a new data-frame (df3) the same way in order to keep the original df1 to reuse it later.

for i in df1.columns:
    df3[i] = df1[i]*df2['Weights']

Upvotes: 1

Related Questions