Pandas custom exponential decay

Viewed 50

Suppose I have the following dataframe.

df = pd.DataFrame({"a": [1, 0, 0, 2, 0]})

I want to construct a new dataframe based on df such that

newdf[0] = 1 or nan
newdf[1] = 0 + newdf[0] * exp(-alpha) # Alpha is some value.
newdf[2] = 0 + newdf[1] * exp(-alpha)
newdf[3] = 2 + newdf[2] * exp(-alpha)
newdf[4] = 0 + newdf[3] * exp(-alpha)

Basically I want to construct a new dataframe which accepts instanteneous change and decay its own value.

Is there an elegant way to achieve this using pd.rolling or pd.ewm? I'd like to avoid any for-loop because dataframe has many rows and columns.

Thanks

1 Answers

Use -

alpha = 2
df['new'] = 1 or np.nan
df['new'] = df['a'] + df['a'].shift(-1)*np.exp(-alpha)

import numpy as np is a dependency. The last row in the df will by np.nan based on this.

Related