create lag features based on multiple columns

大憨熊 提交于 2019-12-24 06:06:03

问题


i have a time series dataset. i need to extract the lag features. i am using below code but got all NAN's

df.groupby(['week','id1','id2','id3'],as_index=False)['value'].shift(1)

input

week,id1,id2,id3,value
1,101,123,001,45
1,102,231,004,89
1,203,435,099,65
2,101,123,001,48
2,102,231,004,75
2,203,435,099,90

output

week,id1,id2,id3,value,t-1
1,101,123,001,45,NAN
1,102,231,004,89,NAN
1,203,435,099,65,NAN
2,101,123,001,48,45
2,102,231,004,75,89
2,203,435,099,90,65

回答1:


You want to shift to the next week so remove 'week' from the grouping:

df['t-1'] = df.groupby(['id1','id2','id3'],as_index=False)['value'].shift()
#    week  id1  id2  id3  value   t-1
#0     1  101  123    1     45   NaN
#1     1  102  231    4     89   NaN
#2     1  203  435   99     65   NaN
#3     2  101  123    1     48  45.0
#4     2  102  231    4     75  89.0
#5     2  203  435   99     90  65.0

That's error prone to missing weeks. In this case we can merge after changing the week, which ensures it is the prior week regardless of missing weeks.

df2 = df.assign(week=df.week+1).rename(columns={'value': 't-1'})
df = df.merge(df2, on=['week', 'id1', 'id2', 'id3'], how='left')

Another way to bring and rename many columns would be to use the suffixes argument in the merge. This will rename all overlapping columns (that are not keys) in the right DataFrame.

df.merge(df.assign(week=df.week+1),         # Manally lag
         on=['week', 'id1', 'id2', 'id3'], 
         how='left',
         suffixes=['', '_lagged']           # Right df columns -> _lagged
         )
#   week  id1  id2  id3  value  value_lagged
#0     1  101  123    1     45           NaN
#1     1  102  231    4     89           NaN
#2     1  203  435   99     65           NaN
#3     2  101  123    1     48          45.0
#4     2  102  231    4     75          89.0
#5     2  203  435   99     90          65.0


来源:https://stackoverflow.com/questions/58295815/create-lag-features-based-on-multiple-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!