Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas Multiply 2D by 1D Dataframe

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 =

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading