3
                  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".

Lcy
  • 335
  • 2
  • 3
  • 10
  • 1
    suppose you have a window of length 30, do you want to calculate the mean with respect to the not trues within that length 30 window. Meaning the window will be subset to less than 30? Or do you want to gather 30 periods, skipping over the `True`s? – piRSquared Feb 02 '17 at 16:53
  • the latter one. I want to gather 30 False periods, skipping over Trues. – Lcy Feb 03 '17 at 02:40
  • Then @ASGM has your answer. – piRSquared Feb 03 '17 at 02:40
  • @piRSquared what about how to do the first one of the mean with respect to the not trues. – Anflores Aug 28 '19 at 13:07
  • @Anflores `df.Data.mask(df.flag).rolling(30, min_periods=1).mean()` does it. However, the minimum period of `1` means that it will take the mean for for the first 29 truncated rolling observations. You may want to `df.Data.mask(df.flag).rolling(30, min_periods=1).mean().iloc[29:].reindex(df.index)` – piRSquared Aug 28 '19 at 13:34

1 Answers1

4

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)
ASGM
  • 11,051
  • 1
  • 32
  • 53