Computing diffs within groups of a dataframe

前端 未结 6 394
你的背包
你的背包 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:39

    I know this is an old question, so I'm assuming this functionality didn't exist at the time. But for those with this question now, this solution works well:

    df.sort_values(['ticker', 'date'], inplace=True)
    df['diffs'] = df.groupby('ticker')['value'].diff()
    

    In order to return to the original order, you can the use

    df.sort_index(inplace=True)
    

提交回复
热议问题