0

I have this dataframe. I need to replace NaNs in column rank to a value based on multiple conditions. If column min is higher than 3 previous rows of max column then rank equals to min. Otherwise, I need to copy the previous value of rank

      max     min    rank
0  128.20  117.87  117.87
1  132.72  122.29  122.29
2  138.07  124.89  124.89
3  137.02  128.46     NaN
4  130.91  129.86     NaN
5  200.15  190.54     NaN
6  199.18  191.79     NaN
7  210.44  201.94     NaN

The desired result is

      max     min    rank
0  128.20  117.87  117.87
1  132.72  122.29  122.29
2  138.07  124.89  124.89
3  137.02  128.46  124.89
4  130.91  129.86  124.89
5  200.15  190.54  190.54
6  199.18  191.79  190.54
7  210.44  201.94  201.94 

2 Answers 2

1

IIUC, here's one way:

df['rank'].mask(pd.concat([df['min'].shift(i) for i in range(3)], 1).apply(
    lambda x: x < df['min']).all(1), df['min']).ffill()
OUTPUT:
      max     min    rank
0  128.20  117.87  117.87
1  132.72  122.29  122.29
2  138.07  124.89  124.89
3  137.02  128.46  124.89
4  130.91  129.86  124.89
5  200.15  190.54  190.54
6  199.18  191.79  190.54
7  210.44  201.94  201.94
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, simly perfect
1

You can try:

df["rank"].update(df[df["min"]>df["max"].rolling(3).max().shift(1)]["min"])
df["rank"].ffill(inplace=True)
>>> df
      max     min    rank
0  128.20  117.87  117.87
1  132.72  122.29  122.29
2  138.07  124.89  124.89
3  137.02  128.46  124.89
4  130.91  129.86  124.89
5  200.15  190.54  190.54
6  199.18  191.79  190.54
7  210.44  201.94  201.94

The rolling and shift functions are being used to check if the current min is greater than the max of the three previous max.

The ffill carries forward the previous value.

1 Comment

Thank you, works perfectly. I chose another answer as correct just because it is only one line of code, but yours also works without any problems

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.