Peslier53
Peslier53

Reputation: 619

Apply a function on a pandas column

I have created the function below which returns a vector based on two input vectors. I have a pandas dataframe with different columns and I would like to apply that function to some columns of my dataframe (one pandas column would be the first vector of my function (nominal), another one the second vector of my function(CPI) and I would assign the result of my function to a new pandas column). How could I do it?

Thank you very much for your help,

Pierre

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

Upvotes: 1

Views: 141

Answers (1)

jezrael
jezrael

Reputation: 863501

You can use cumprod for vectorized solution:

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

Upvotes: 1

Related Questions