data = {'Open': [7099,7089.3,7097.55,7365,7429, 7486.05], 'high': [ 7150,7169,7278.2,7410,7500,7520], 'low' : [7060,6884.85,7092.25,7344.15,7407,7443],
'close': [7104,7058.4,7269.1,7398.3,7489.45,7505.45]}
df1 = pd.DataFrame(data)
I want to calculate (open-close(previous row) in another column 'gap'. in Excel we can easily refer the previous cell to get the out put as below C12-F11.
is anyway to achieve this without using loop ? similar to numpy function np.where()
df1["open=high"] = np.where (df1['open'] == df1 ['high'], 'Y', 'N')
CodePudding user response:
You can use shift:
df1['Gap'] = df1.Open - df1.close.shift()
df1
Open high low close Gap
0 7099.00 7150.0 7060.00 7104.00 NaN
1 7089.30 7169.0 6884.85 7058.40 -14.70
2 7097.55 7278.2 7092.25 7269.10 39.15
3 7365.00 7410.0 7344.15 7398.30 95.90
4 7429.00 7500.0 7407.00 7489.45 30.70
5 7486.05 7520.0 7443.00 7505.45 -3.40