2

I am trying to create a column called "Threshold" where the values are determined by calculation df['column']/30**0.5 , but I want this column to have a minimum value of 0.2. So if the calculation is below 0.2, I want the column value to be 0.2.

For example: df['column2'] = (df['column']/30)**0.5 or 0.2 (which ever number is larger).

This is what I have currently:

df['Historical_MovingAverage_15'] = df['Historical_Average'].rolling(window=15).mean()
df['Threshold'] = max((((df['Historical_MovingAverage_15'])/30)**0.5), 0.2)

It gives me this error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

1 Answer 1

4

Use numpy.maximum:

df['Threshold'] = np.maximum((((df['Historical_MovingAverage_15'])/30)**0.5), 0.2)

Or Series.clip with lower parameter:

df['Threshold'] = (((df['Historical_MovingAverage_15'])/30)**0.5).clip(lower=0.2)

Sample:

df = pd.DataFrame({'Historical_MovingAverage_15':[.21,2,3]})
df['Threshold'] = np.maximum((((df['Historical_MovingAverage_15'])/30)**0.5), 0.2)
print (df)
   Historical_MovingAverage_15  Threshold
0                         0.21   0.200000
1                         2.00   0.258199
2                         3.00   0.316228

Detail:

print ((((df['Historical_MovingAverage_15'])/30)**0.5))
0    0.083666
1    0.258199
2    0.316228
Name: Historical_MovingAverage_15, dtype: float64
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I decided to use .clip() since I don't need to import another library. Works perfectly.
Filtering can also be done with apply: df[df["column"].apply(lambda x: return x >= 0.2)]

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.