Rolling difference in Pandas

前端 未结 4 1684
忘了有多久
忘了有多久 2020-12-10 13:39

Does anyone know an efficient function/method such as pandas.rolling_mean, that would calculate the rolling difference of an array

This is my closest so

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-10 14:04

    What about:

    import pandas
    
    x = pandas.DataFrame({
        'x_1': [0, 1, 2, 3, 0, 1, 2, 500, ],},
        index=[0, 1, 2, 3, 4, 5, 6, 7])
    
    x['x_1'].rolling(window=2).apply(lambda x: x.iloc[1] - x.iloc[0])
    

    in general you can replace the lambda function with your own function. Note that in this case the first item will be NaN.

    Update

    Defining the following:

    n_steps = 2
    def my_fun(x):
        return x.iloc[-1] - x.iloc[0]
    
    x['x_1'].rolling(window=n_steps).apply(my_fun)
    

    you can compute the differences between values at n_steps.

提交回复
热议问题