0

I have a dataframe:

A     B
100   0.00
50   -0.50
100   1.00
120   0.20                              

I would like to select shifted values on the A column based on a certain condition on the B column, so for instance if B >= 0.20 and my desired shift step is 2 I would get 100 (from B =1.00) and 50 (from B = 0.20 ), rows where B < 0.20 can be discarded.

2
  • 1
    Can you give a bit more context? Do you have multiple shift values you need to implement in some sort of if-else logic? Or are we just leaving anything <0.2 NaN? Commented May 28, 2019 at 1:11
  • @ALollz: Not interested in those rows, they could be NaN's or left out ( but I can do that later on a new df I suppose), edited the question, thx. Commented May 28, 2019 at 1:20

1 Answer 1

1

You can use shift with np.where to conditionally get the shifted values:

shiftstep = 2

df['shift'] = np.where(df['B'].ge(0.2), df['A'].shift(shiftstep), np.NaN)

     A    B  shift
0  100  0.0    NaN
1   50 -0.5    NaN
2  100  1.0  100.0
3  120  0.2   50.0
Sign up to request clarification or add additional context in comments.

2 Comments

Works like a charm, I wasn't aware of the ge operator...pandas.pydata.org/pandas-docs/stable/reference/api/…
Note: It turns out that I also needed the opposite selection, using a negative'shiftstep works !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.