conditional EMA pandas dataframe

Viewed 25

I have a pandas dataframe that looks like this:

condition Value
2016-01-01 10:01:00 True 1
2016-01-01 10:02:00 False 2
2016-01-01 10:03:00 True 3
2016-01-01 10:04:00 False 4
2016-01-01 10:05:00 False 5
2016-01-01 10:06:00 False 6
2016-01-01 10:07:00 False 7
2016-01-01 10:08:00 False 8
2016-01-01 10:09:00 False 9
2016-01-01 10:10:00 True 10

Here is the code to build the df I typed above:

df = pd.DataFrame({
                  'year': [2016]*10,
                  'month': [1]*10,
                  'day' : [1]*10,
                  'hour': [10]*10,
                  'minute': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]})
df.index = pd.to_datetime(df)
df['condition'] = [True, False, True, False, False, False, False, False, False, True]
df['value'] = [1,2,3,4,5,6,7,8,9,10]
df = df[['condition', 'value']]

I want to have a column that shows the exponentially weighted moving average (halflife=5minutes) of values when the condition column is True.

Any help would be appreciated!

1 Answers

Figured out:

df['value_conditional'] = np.where(
    df['condition'] == True,
    df['value'],
    0
)

df['ewm_conditional'] = df.ewm(halflife=dt.timedelta(minutes=5), times=df.index).value_conditional.mean()
Related