Skip to content
Advertisement

Fast way to cyclically wrap values in pandas dataframe

In words: I have a data frame that consists of values over a day, for multiple days per Userid. I’d like to shift all of certain people’s data by 1 period, so that the first value in their first column is a nan, and then everything is cyclically offset, with the last value truncated or lost to space and time, whichever is faster.

What I’m currently doing is slow, because I end up iterating over all of the rows of the people I’m interested in. I wonder if there is not a faster solution I’m not thinking of.

In code:

Given this dataset:

JavaScript

I currently use the following code to shift the values for certain ids:

JavaScript

Which achieves the following:

JavaScript

The problem is that shift_by_1 is slow. I feel like there has to be a faster way, maybe through a group-by + clever use of lambda and something like np.ravel() and its opposite?

Any and all help is much appreciated, thanks in advance.

Advertisement

Answer

IIUC:

JavaScript

Output:

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