0

I have the code below which works to update a dataframe column 'flag' to yes or no based on a rolling window calculation of column 'A' (rolling window value value in 'A' should have a min >100 and max <200 to get yes value, otherwise value is no:

df['flag'] = np.where(
                     ((df['A'].rolling(60).apply(lambda s: s.min()))> 50) &
                     ((df['A'].rolling(60).apply(lambda s: s.max()))< 100)
                     ,'yes', 'no')

Now I just need to change it so if condition is not met it does not update the df['flag'] value, instead of writing 'no'. Or maybe there is a whole different method to accomplish the same thing?

1
  • 1
    As per the suggested duplicate, you use df.loc[m, 'flag'] = 'yes' for this (where m is your mask). Commented Oct 15, 2024 at 20:00

2 Answers 2

1

You can use loc method to reach tis

df = pd.DataFrame({
    'A': np.random.randint(50, 150, size=200)
})

df['flag'] = ''

mask = ((df['A'].rolling(60).apply(lambda s: s.min()) > 100) &
        (df['A'].rolling(60).apply(lambda s: s.max()) < 200))

df.loc[mask, 'flag'] = 'yes'
Sign up to request clarification or add additional context in comments.

Comments

1

You can use pandas .mask which retains the original value if the condition is not met :

df['flag'] = df['flag'].mask(
                     ((df['A'].rolling(60).apply(lambda s: s.min()))> 50) &
                     ((df['A'].rolling(60).apply(lambda s: s.max()))< 100)
                     ,'yes')

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.