If we have a Pandas DataFrame containing the following values
x
date
2017-07-30 1
2017-07-31 2
2017-08-01 3
2017-08-02 4
how can we create a new column y whose value is calculated using
today's y = 2*(previous day's y) + (today's x)
for the oldest date, y will be 1
Expected Result:
x y
date
2017-07-30 1 1
2017-07-31 2 4
2017-08-01 3 11
2017-08-02 4 26
Attempt:
import pandas as pd
d = {
'date': ['2017-07-30', '2017-07-31', '2017-08-01', '2017-08-02'],
'x': [1,2,3,4]
}
df = pd.DataFrame.from_dict(d).set_index('date')
df['y'] = 1
df['y'] = df['y'].shift(1)*2 + df['x']
print(df)
Attempt's Result
x y
date
2017-07-30 1 NaN
2017-07-31 2 4.0
2017-08-01 3 5.0
2017-08-02 4 6.0