Skip to content
Advertisement

Groupby and lag all columns of a dataframe?

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

JavaScript

which looks like

JavaScript

and I want it to look like this:

JavaScript

This question manages the result for a single column, but I have an arbitrary number of columns, and I want to lag all of them. I can use groupby and apply, but apply runs the shift function over each column independently, and it doesn’t seem to like receiving an [nrow, 2] shaped dataframe in return. Is there perhaps a function like apply that acts on the whole group sub-frame? Or is there a better way to do this?

Advertisement

Answer

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

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement