0

I want to get the value of the ‘shift’ column as an argument to the function shift

I try to

df['gg_shift']=df['gg'].shift(df['shift'])

but it doesn't work

expected result table

gg      bool    shift   gg_shift
0.88    FALSE   0   
0.87    TRUE    0   
0.94    FALSE   1       0.87
0.17    FALSE   2       0.87
0.92    TRUE    0   
0.51    FALSE   1       0.92
0.1     TRUE    0   
0.88    FALSE   1       0.1
0.36    FALSE   2       0.1
0.14    TRUE    0   
        
junyu
  • 89
  • 5
  • I found someone else's solution https://stackoverflow.com/questions/50970476/comparing-values-from-pandas-data-frame-column-using-offset-values-from-another/50972089#50972089 – junyu Jul 07 '22 at 15:18

2 Answers2

1

Because only scalar is possible pass to Series.shift get unique values of shift without 0 (no shift) and assign only match condition:

for x in df.loc[df['shift'].ne(0), 'shift'].unique():
    m = df['shift'].eq(x)
    df.loc[m, 'gg_shift'] = df['gg'].shift(x)
    
print (df)
     gg   bool  shift  gg_shift
0  0.88  False      0       NaN
1  0.87   True      0       NaN
2  0.94  False      1      0.87
3  0.17  False      2      0.87
4  0.92   True      0       NaN
5  0.51  False      1      0.92
6  0.10   True      0       NaN
7  0.88  False      1      0.10
8  0.36  False      2      0.10
9  0.14   True      0       NaN
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
1

I might be misinterpreting your logic, but it looks like you want to get the gg values of the previous True for all False.

If this is the case you do not need to use the shift column, simply ffill and mask the data:

df['gg_shift'] = df['gg'].where(df['bool']).ffill().mask(df['bool'])

output:

     gg   bool  shift  gg_shift
0  0.88  False      0       NaN
1  0.87   True      0       NaN
2  0.94  False      1      0.87
3  0.17  False      2      0.87
4  0.92   True      0       NaN
5  0.51  False      1      0.92
6  0.10   True      0       NaN
7  0.88  False      1      0.10
8  0.36  False      2      0.10
9  0.14   True      0       NaN
mozway
  • 194,879
  • 13
  • 39
  • 75
  • This is a good idea, my logic is that if I can get the position based on shift, I can get any column at that position – junyu Jul 06 '22 at 11:15