Home > database >  How to pass column value as parameter for rolling or shift
How to pass column value as parameter for rolling or shift

Time:12-04

Input:

import pandas as pd
import numpy as np
df=pd.DataFrame(np.random.rand(10,1),columns = ['A'])
df['pos']=[0,0,1,2,0,0,1,2,3,4]

I try to

df.A.rolling(df['pos']).max()
or
df.A.shift(df['pos'])

It doesn't work, how to achieve it?

CodePudding user response:

According to the documentation, both the rolling and shift operations are sequence-to-sequence transformations. If you want to produce a series of sequences based on the integer parameters in pos, you need to repeat this operation:

pd.DataFrame({f'seq {i}': df.A.shift(i) for i in df.pos})
  • Related