Abhishek Soam
Abhishek Soam

Reputation: 3

Use previous values of rows in data frame to build the current cell value

I have a dataframe as represented here

   A     
0.001216  
0.000453
0.00506
0.004556
0.005266

I want to create a new column B something according to this formula presented in the code below.

column_key = 'B'
factor = 'A' 
df[column_key] = np.nan
df[column_key][0] = (df[factor][0] + 1) * 100
for i in range(1, len(df)):
    df[column_key][i] = (df[factor][i] + 1) * df[column_key][i-1]

I have been trying to fill the current cell value using the previous cell of a column and adjacent cell of a column.

This is what I have tried but I don't think this is going to be effective.

Can anyone help me with best efficient approach of solving this problem?

Upvotes: 0

Views: 45

Answers (1)

Rajat Jain
Rajat Jain

Reputation: 2032

Using pandas.cumprod(), it can be done in following way:

df['B'] = df['A'] + 1
df['B'][0] = df['B'][0] * 100
df['B'] = df['B'].cumprod()

Upvotes: 1

Related Questions