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
>>>
这不会得到同样的事情吗?
df = df * MultFactor
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.