How to create a lagged data structure using pandas dataframe

后端 未结 8 2254
耶瑟儿~
耶瑟儿~ 2020-12-04 15:24

Example

s=pd.Series([5,4,3,2,1], index=[1,2,3,4,5])
print s 
1    5
2    4
3    3
4    2
5    1

Is there an efficient way to create a serie

8条回答
  •  南方客
    南方客 (楼主)
    2020-12-04 16:10

    Assuming you are focusing on a single column in your data frame, saved into s. This shortcode will generate instances of the column with 7 lags.

    s=pd.Series([5,4,3,2,1], index=[1,2,3,4,5], name='test')
    shiftdf=pd.DataFrame()
    for i in range(3):
        shiftdf = pd.concat([shiftdf , s.shift(i).rename(s.name+'_'+str(i))], axis=1)
    
    shiftdf
    
    >>
    test_0  test_1  test_2
    1   5   NaN NaN
    2   4   5.0 NaN
    3   3   4.0 5.0
    4   2   3.0 4.0
    5   1   2.0 3.0
    

提交回复
热议问题