我创建了下面的函数,它根据两个输入向量返回一个向量。我有一个包含不同列的pandas数据帧,我想将该函数应用于我的数据帧的某些列(一个pandas列将是我的函数的第一个向量(标称值),另一个是我的函数的第二个向量(CPI)和我会将我的函数的结果分配给一个新的pandas列)。我怎么能这样做?
非常感谢你的帮助,
皮埃尔
nominal=[10,10,10,10,10,10,10,10,10,10,10,10]
CPI=[0.02,0.02,0.02,0.02,0.02,0.02,0.02,0.02,0.02,0.02,0.02,0.02]
def nominal_to_real(nominal,CPI):
real=[]
product=1
for i in range(len(nominal)):
product*=(CPI[i]+1)**(1/12)
real.append(nominal[i]/product)
return real
答案 0 :(得分:1)
您可以将cumprod
用于矢量化解决方案:
nominal=[10,10,10,10,10,10,10,10,10,10,10,10]
CPI=[0.02,0.02,0.02,0.02,0.02,0.02,0.02,0.02,0.02,0.02,0.02,0.02]
def nominal_to_real(nominal,CPI):
real=[]
product=1
for i in range(len(nominal)):
product*=(CPI[i]+1)**(1/12)
real.append(nominal[i]/product)
return real
a = nominal_to_real(nominal,CPI)
df = pd.DataFrame(np.c_[nominal, CPI, a], columns=['nominal','CPI','real'])
df['real1'] = df['nominal'] / ((df['CPI'] + 1)**(1/12)).cumprod()
print (df)
nominal CPI real real1
0 10.0 0.02 9.983511 9.983511
1 10.0 0.02 9.967050 9.967050
2 10.0 0.02 9.950616 9.950616
3 10.0 0.02 9.934209 9.934209
4 10.0 0.02 9.917829 9.917829
5 10.0 0.02 9.901475 9.901475
6 10.0 0.02 9.885149 9.885149
7 10.0 0.02 9.868850 9.868850
8 10.0 0.02 9.852578 9.852578
9 10.0 0.02 9.836332 9.836332
10 10.0 0.02 9.820114 9.820114
11 10.0 0.02 9.803922 9.803922