Python通过减去上一个日期pri来计算新列的值

2024-03-29 12:10:29 发布

您现在位置:Python中文网/ 问答频道 /正文

这里有股票的开盘价和收盘价:

Open        Close
1994.988    1994.988
2020.8496   2006.1270142499998
2050.030029 2017.3700764583332
2041.51001  2039.3920492708332
2062.52002  2057.9604493541665
2055.469971 2058.56656934375
2046.73998  2059.327636895833

现在,我必须创建一个新的列“Percent\u Change”,它将被计算为 (关闭-打开)/打开。你知道吗

应该对前一天的值进行计算,所以第一行将是Nan,然后是0,依此类推。。。你知道吗

Per_Change
NaN
0
-0.73%
-1.59%
-0.10%
-0.22%
0.15%
0.62%

Tags: closeopennanchange股票percentper收盘价
2条回答
def compute_precent(row):
    return(float(row[1]-row[0])/row[0])
df['percentage_change']=df.apply(lambda x:compute_precent(x),axis=1)

可以使用^{}移动结果:

df['PctChange'] = ((df['Close'] - df['Open']) / df['Close']).shift()

print(df)

          Open        Close  PctChange
0  1994.988000  1994.988000        NaN
1  2020.849600  2006.127014   0.000000
2  2050.030029  2017.370076  -0.007339
3  2041.510010  2039.392049  -0.016189
4  2062.520020  2057.960449  -0.001039
5  2055.469971  2058.566569  -0.002216
6  2046.739980  2059.327637   0.001504

预期结果的最后一行必然会丢失,因为数据帧索引/长度没有改变。你知道吗

相关问题 更多 >