pandas Python -类似于excel公式,如何通过引用前一行在python/panda中对每行进行计算

c0vxltue  于 2023-01-07  发布在  Python
关注(0)|答案(1)|浏览(131)
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)

我想计算(打开-关闭(前一行)在另一列'差距'。在Excel中,我们可以很容易地参考前一个单元格,以获得输出如下C12-F11。
是不是不用循环就能达到这个目的?类似于numpy函数np.where()

df1["open=high"] = np.where (df1['open'] == df1 ['high'], 'Y', 'N')

mcvgt66p

mcvgt66p1#

您可以使用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

相关问题