Pandas pct_change gives slightly different answers to manual

旧时模样 提交于 2019-12-11 08:48:49

问题


Can anyone explain why the pct_change function gives slightly different numbers when using the more manual calculation:

pct_change function:

print(prices)
         0                                                                    
0   1035.23                                                                    
1   1032.47                                                                    


print(prices.pct_change(1))

          0                                                                   
0        NaN                                                                   
1  -0.002666                                                                   

More manual function

(prices - prices.shift(1))/prices

          0                                                                   
0        NaN                                                                   
1  -0.002673 

What is the reason behind the difference here?


回答1:


Problem is second formula is wrong:

prices = pd.DataFrame({0:[1035.23,1032.47]})
print (prices)

print(prices.pct_change(1))
          0
0       NaN
1 -0.002666

print(prices/(prices.shift())-1)
          0
0       NaN
1 -0.002666

As pointed Andrew L in comment:

print((prices - prices.shift(1))/prices.shift(1))
          0
0       NaN
1 -0.002666


来源:https://stackoverflow.com/questions/45437284/pandas-pct-change-gives-slightly-different-answers-to-manual

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!