Rolling difference in Pandas

前端 未结 4 1687
忘了有多久
忘了有多久 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 13:54

    This should work:

    import numpy as np
    
    x = np.array([1, 3, 6, 1, -5, 6, 4, 1, 6])
    
    def running_diff(arr, N):
        return np.array([arr[i] - arr[i-N] for i in range(N, len(arr))])
    
    running_diff(x, 4)  # array([-6,  3, -2,  0, 11])
    

    For a given pd.Series, you will have to define what you want for the first few items. The below example just returns the initial series values.

    s_roll_diff = np.hstack((s.values[:4], running_diff(s.values, 4)))
    

    This works because you can assign a np.array directly to a pd.DataFrame, e.g. for a column s, df.s_roll_diff = np.hstack((df.s.values[:4], running_diff(df.s.values, 4)))

提交回复
热议问题