How calculate a value using a previous values in pandas dataframe

Question:

I am trying to calculate a value in a pandas dataframe using the previous value. Given the values below:

year sex age pxt lxt
2000 m 0 m x
2000 m 1 n y
2000 m 2 o z
x = 1 (by definition)

y = x * m

z = y * n

I tried to use the .shift(1) method, which worked for the pxt, but since the lxt is calculated iterativly, this did not work in this case.

And yes, data are grouped by year and sex.

Thank you very much!

Asked By: as_meth

||

Answers:

You need to shift filling with your starting value, then cumprod:

df['lxt'] = df['pxt'].shift(fill_value=1).cumprod()

Example output:

   year sex  age  pxt  lxt
0  2000   m    0   10    1
1  2000   m    1   20   10
2  2000   m    2   30  200
Answered By: mozway
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.