Reputation: 123
I'm trying to multiply 2 dataframes (herebelow)
df1
df2
and I'm expecting something like this as a result:
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
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
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