Looking for an elegant way to multiply a 2D dataframe by a 1D series where the indices and column names align
df1 =
Index | A | B |
---|---|---|
1 | 1 | 5 |
2 | 2 | 6 |
3 | 3 | 7 |
4 | 4 | 8 |
df2 =
Coef | |
---|---|
A | 10 |
B | 100 |
Something like...
df3 = df1.mul(df2)
To get :
Index | A | B |
---|---|---|
1 | 10 | 500 |
2 | 20 | 600 |
3 | 30 | 700 |
4 | 40 | 800 |
CodePudding user response:
There is no such thing as 1D DataFrame, you need to slice as Series to have 1D, then multiply
(by default on axis=1
):
df3 = df1.mul(df2['Coef'])
Output:
A B
1 10 500
2 20 600
3 30 700
4 40 800
If Index is a column:
df3 = df1.mul(df2['Coef']).combine_first(df1)[df1.columns]
Output:
Index A B
0 1.0 10.0 500.0
1 2.0 20.0 600.0
2 3.0 30.0 700.0
3 4.0 40.0 800.0