pythonpandasconditional-statementssliding

Conditional mean by rolling


                  Data       flag
2017-01-01        17.2        False     
2017-01-02        17.0        False      
2017-01-03        16.8        False   
2017-01-04        18.3        False      
2017-01-05        19.1        True       
...
2017-12-28        20.1        False      
2017-12-29        19.8        False      
2017-12-30        18.9        False      
2017-12-31        19.5        False      

There is a pandas dataframe that has values and flag. I want to calculate mean values by rolling(window=30), if the flag is "NOT TRUE".


Solution

  • You can use pandas.rolling_mean() while subsetting the dataframe to only include entries where df.flag is false (the ~ operator inverts the truth of the boolean series, getting all values where df.flag is False).

    pandas.rolling_mean(df[~df.flag], window=30)