分配给 Pandas 中的分组数据框

assign to grouped dataframe in Pandas

我想计算多列的滞后。我可以分别为每一列执行此操作,如下所示。如何避免重复的 groupby 和排序。

### Pandas previous week values

search  = search.assign(asp_lstwk2 = search.sort_values(by = 'firstdayofweek').groupby('asin_bk')['asp'].shift(1))\
                 .assign(lbb_lstwk2 = search.sort_values(by = 'firstdayofweek').groupby('asin_bk')['lbb'].shift(1))\
                .assign(repoos_lstwk2 = search.sort_values(by = 'firstdayofweek').groupby('asin_bk')['repoos'].shift(1))\
                .assign(ordered_units_lstwk2 = search.sort_values(by = 'firstdayofweek').groupby('asin_bk')['ordered_units'].shift(1))

尝试:

search = search.join(search.sort_values(by = 'firstdayofweek')
                     .groupby('asin_bk')[['asp','lbb','repoos','ordered_units']]
                     .shift().add_suffix('_lstwk2'))