1

I have the following dataframe:

>>> import numpy as np
>>> import pandas as pd
>>> df=pd.DataFrame()
>>> df['Var1']=np.random.randint(0,100,10)    
>>> df['Var2']=np.random.randint(0,10,10)   
>>> df
   Var1  Var2
0    46     2
1    10     3
2    30     6
3    49     4
4    62     3
5    64     8
6    26     0
7    41     2
8     3     2
9    22     3
>>> 

And I have the following series that contains multiplication factors that each column will be multiplied by:

>>> MultFactors=pd.Series(index=['Var1','Var2'],data=np.random.randn(2))
>>> MultFactors
Var1    0.833691
Var2   -1.408577
dtype: float64
>>> 

What is the best way to return a dataframe that is the same shape as the original dataframe and contains each value multiplied by the appropriate multiplication factor. I can do this with a for loop but am wondering what the more efficient way is.

>>> for MultFactor in MultFactors.index:
...     df[MultFactor]=df[MultFactor]*MultFactors[MultFactor]
... 
>>> df
        Var1       Var2
0  38.349773  -2.817155
1   8.336907  -4.225732
2  25.010722  -8.451464
3  40.850845  -5.634310
4  51.688825  -4.225732
5  53.356206 -11.268619
6  21.675959  -0.000000
7  34.181319  -2.817155
8   2.501072  -2.817155
9  18.341196  -4.225732
>>> 
1

1 Answer 1

3

Won't this get the same thing?

df = df * MultFactor
Sign up to request clarification or add additional context in comments.

2 Comments

Wow. Yes - a lot easier than I had thought.
As long as the variable names match it will multiply matching variables.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.