Groupby and lag all columns of a dataframe?

前端 未结 1 742
Happy的楠姐
Happy的楠姐 2021-02-19 12:07

I want to lag every column in a dataframe, by group. I have a frame like this:

import numpy as np
import pandas as pd

index = pd.date_range(\'2015-11-20\', peri         


        
相关标签:
1条回答
  • 2021-02-19 12:51

    IIUC, you can simply use level="grp" and then shift by -1:

    >>> shifted = df.groupby(level="grp").shift(-1)
    >>> df.join(shifted.rename(columns=lambda x: x+"_lag"))
                    col1 col2  col1_lag col2_lag
    time       grp                              
    2015-11-20 A       1    a         2        b
    2015-11-21 A       2    b         3        c
    2015-11-22 A       3    c       NaN      NaN
    2015-11-23 B       1    a         2        b
    2015-11-24 B       2    b         3        c
    2015-11-25 B       3    c       NaN      NaN
    
    0 讨论(0)
提交回复
热议问题