Computing diffs within groups of a dataframe

前端 未结 6 399
你的背包
你的背包 2020-11-30 19:21

Say I have a dataframe with 3 columns: Date, Ticker, Value (no index, at least to start with). I have many dates and many tickers, but each (ticker, date) tupl

6条回答
  •  半阙折子戏
    2020-11-30 19:43

    # Make sure your data is sorted properly
    df = df.sort_values(by=['group_var', 'value'])
    
    # only take diffs where next row is of the same group
    df['diffs'] = np.where(df.group_var == df.group_var.shift(1), df.value.diff(), 0)
    

    Explanation:

提交回复
热议问题