How do I subtract the previous row from the current row in a pandas dataframe and apply it to every row; without using a loop?

后端 未结 2 597
失恋的感觉
失恋的感觉 2021-02-03 23:56

I am using Python3.5 and I am working with pandas. I have loaded stock data from yahoo finance and have saved the files to csv. My DataFrames load this data from the csv. This

相关标签:
2条回答
  • 2021-02-04 00:25

    MaxU solutions suits in your case. If you want to perform more complex computations based on your previous rows you should use shift

    0 讨论(0)
  • 2021-02-04 00:29

    you can use pct_change() or/and diff() methods

    Demo:

    In [138]: df.Close.pct_change() * 100
    Out[138]:
    0         NaN
    1    0.469484
    2    0.467290
    3   -0.930233
    4    0.469484
    5    0.467290
    6    0.000000
    7   -3.255814
    8   -3.365385
    9   -0.497512
    Name: Close, dtype: float64
    
    In [139]: df.Close.diff()
    Out[139]:
    0      NaN
    1    0.125
    2    0.125
    3   -0.250
    4    0.125
    5    0.125
    6    0.000
    7   -0.875
    8   -0.875
    9   -0.125
    Name: Close, dtype: float64
    
    0 讨论(0)
提交回复
热议问题