Can you use pandas to iterate over a dataframe while multiplying the previous row by a value?

Viewed 67

As of now, I produced the below dataframe using python's pandas:

ID Revenue
1 50000
2 50000
3 50000
4 50000

My end goal would be to produce the table below. The logic would be to iterate over the dataframe and have it execute the below formula. For reference, I would like the first row (ID #1) to remain static.

Formula: (Prior Row * 10%) + Prior Row

ID Revenue
1 50000
2 55000
3 60500
4 66550
2 Answers

We can create a range of values based on the length of the DataFrame take the percentage to the power of this array then multiply by Revenue:

import numpy as np
import pandas as pd

df = pd.DataFrame({
    'ID': [1, 2, 3, 4], 'Revenue': [50000, 50000, 50000, 50000]
})

percent = .1
df['Revenue'] = df['Revenue'] * ((1 + percent) ** np.arange(len(df)))

df:

   ID  Revenue
0   1  50000.0
1   2  55000.0
2   3  60500.0
3   4  66550.0

The operation:

(1 + percent) ** np.arange(len(df))

produces the current cumulative percentage at each row of the DataFrame:

[1.    1.1   1.21  1.331]

This is used to determine the current cumulative percentage by which to multiply Revenue.


import pandas as pd


df = pd.DataFrame({"ID": range(1,6), "Revenue":[50000]*5})
df["Revenue"] = df[["ID", "Revenue"]].apply(lambda x: x[1]*(1.1**(x[0]-1)),axis=1)

Related