df.rolling(7, center=True).mean()

The rolling mean can be centered by setting the center argument to True.

Example plot

Answer from abrac on Stack Overflow
Top answer
1 of 3
11

Try the following (tested with pandas==0.23.3):

series.rolling('7D', min_periods=1, closed='left').sum().shift(-84, freq='h')

This will center your rolling sum in the 7-day window (by shifting -3.5 days), and will allow you to use a 'datetimelike' string for defining the window size. Note that shift() only takes an integer, thus defining with hours.

This will produce your desired output:

series.rolling('7D', min_periods=1, closed='left').sum().shift(-84, freq='h')['2014-01-01':].head(10)

2014-01-01 12:00:00    4.0
2014-01-02 12:00:00    5.0
2014-01-03 12:00:00    6.0
2014-01-04 12:00:00    7.0
2014-01-05 12:00:00    7.0
2014-01-06 12:00:00    7.0
2014-01-07 12:00:00    7.0
2014-01-08 12:00:00    7.0
2014-01-09 12:00:00    7.0
2014-01-10 12:00:00    7.0
Freq: D, dtype: float64

Note that the rolling sum is assigned to the center of the 7-day windows (using midnight to midnight timestamps), so the centered timestamp includes '12:00:00'.

Another option (as you show at the end of your question) is to resample the data to make sure it has even Datetime frequency, then use an integer for window size (window = 7) and center=True. However, you state that other parts of your code benefit from defining window with a 'datetimelike' string, so perhaps this option is not ideal.

2 of 3
4

From pandas version 1.3 this is * directly possible with pandas.

* Or will be (the work is merged, but 1.3 is not yet released as of today; I tested the lines below against the pandas main branch).

import pandas as pd
series = pd.Series(1, index = pd.date_range('2014-01-01', '2014-04-01', freq = 'D'))
series.rolling(7, min_periods=1, center=True).sum().head(10)

Output is as expected:

2014-01-01    4.0
2014-01-02    5.0
2014-01-03    6.0
2014-01-04    7.0
2014-01-05    7.0
2014-01-06    7.0
2014-01-07    7.0
2014-01-08    7.0
2014-01-09    7.0
2014-01-10    7.0
Freq: D, dtype: float64
🌐
Medium
medium.com › @whyamit101 › understanding-pandas-rolling-f8f6d6796c07
Understanding Pandas Rolling. If you think you need to spend $2,000… | by why amit | Medium
February 26, 2025 - Let me quickly mention them: center: If set to True, the window is centered around the current value. By default, it's False, which means the window is right-aligned (i.e., the calculation is done from the current point to the previous ones).
🌐
datagy
datagy.io › home › pandas tutorials › data analysis in pandas › how to calculate a rolling average (mean) in pandas
How to Calculate a Rolling Average (Mean) in Pandas • datagy
April 2, 2023 - # Plotting the effect of a rolling ... because no data existed for the first six.We can modify this behavior by modifying the center= argument to True....
🌐
GitHub
github.com › pandas-dev › pandas › issues › 18328
Center rolling window that does not include center value · Issue #18328 · pandas-dev/pandas
November 16, 2017 - I need a way to apply a custom function on a rolling dataframe where the centered value is not included. This code below works well, but it does include the center value: import pandas as pd import numpy as np mad = lambda x: np.mean(np.fabs(x - np.median(x))) df = pd.DataFrame([1,1,1,10,1,1,1,2,2,2,2,2,20,2,2,2,2]) df.rolling(3, min_periods=3, center=True).apply(mad)
Author: pandas-dev
🌐
Programiz
programiz.com › python-programming › pandas › methods › rolling
Pandas rolling()
We've set a window size of 3 and ... which means each calculated value is centered on its respective window. Due to the centered approach, the first and last entries don't have both a previous and next value. Hence, their rolling sum is represented as NaN. import pandas as pd # sample ...
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python-pandas-dataframe-rolling
Python | Pandas dataframe.rolling() - GeeksforGeeks
February 21, 2022 - Specified as a frequency string or DateOffset object. center : Set the labels at the center of the window. win_type : Provide a window type. See the notes below. on : For a DataFrame, column on which to calculate the rolling window, rather than the index closed : Make the interval closed on the ‘right’, ‘left’, ‘both’ or ‘neither’ endpoints.
🌐
GitHub
github.com › pandas-dev › pandas › issues › 8269
Unexpected behavior for rolling moments when center=True and min_periods < window · Issue #8269 · pandas-dev/pandas
September 14, 2014 - The reason for this behavior is that _rolling_moment() concats extra NaN values to the end of the input series when center=True to allow the roll_generic() function to continue on past the end of the original series and compute the values that will "come within view" when the result is centered. However, adding those NaN values into the window can bork the calculation and change a result that should be finite into a NaN. ... n = 12 s = Series(np.random.randn(n)) s.plot(color='b') win=7 minp = 5 pd.rolling_mean(s, win, min_periods=minp, center=False).plot(color='g') pd.rolling_mean(s, win, min_periods=minp, center=True).plot(color='r') ticks = plt.xticks(np.arange(0, n, 1.0))
Author: pandas-dev
🌐
GitHub
github.com › pandas-dev › pandas › issues › 20012
Center rolling window with date NotImplementedError · Issue #20012 · pandas-dev/pandas
March 6, 2018 - The rolling window is not able to be centered with a datetimelike index, which is a problem when dealing with time series. I think that this is a WIP feature. I don't see anything blocking about it. ... commit: None python: 3.5.3.final.0 python-bits: 64 OS: Linux OS-release: 4.9.0-3-amd64 machine: x86_64 processor: byteorder: little LC_ALL: None LANG: C.UTF-8 LOCALE: en_US.UTF-8 · pandas...
Author: pandas-dev
🌐
Pandas
pandas.pydata.org › pandas-docs › version › 0.19.2 › generated › pandas.DataFrame.rolling.html
pandas.DataFrame.rolling — pandas 0.19.2 documentation
New in version 0.18.0. ... By default, the result is set to the right edge of the window. This can be changed to the center of the window by setting center=True. The freq keyword is used to conform time series data to a specified frequency by resampling the data.
🌐
Medium
medium.com › @sujathamudadla1213 › explain-in-detail-dataframe-rolling-functions-with-rolling-f22d66966e81
Explain DataFrame rolling functions with rolling(). | by Sujatha Mudadla | Medium
November 17, 2023 - center: A boolean indicating whether the window should be centered on the current date. The default is False, meaning the window is right-aligned. Let’s say you have a DataFrame named df with a column 'value' representing some time-series data.
🌐
Pandas
pandas.pydata.org › pandas-docs › version › 0.22.0 › generated › pandas.DataFrame.rolling.html
pandas.DataFrame.rolling — pandas 0.22.0 documentation
New in version 0.18.0. ... By default, the result is set to the right edge of the window. This can be changed to the center of the window by setting center=True. The freq keyword is used to conform time series data to a specified frequency by resampling the data.
🌐
GitHub
github.com › pandas-dev › pandas › issues › 40313
ENH: Consider adding alternative calculation of centered moving averages for even window size · Issue #40313 · pandas-dev/pandas
March 9, 2021 - (optional) I have confirmed this bug exists on the master branch of pandas. The current rolling(window, center=True).mean() behaviour in Pandas first calculates the rolling mean and then shifts the result back to "center" the labels.
Author: pandas-dev
🌐
Spark By {Examples}
sparkbyexamples.com › home › pandas › pandas rolling() mean, average, sum examples
Pandas rolling() Mean, Average, Sum Examples - Spark By {Examples}
October 14, 2024 - pandas.DataFrame.rolling() function can be used to get the rolling mean, average, sum, median, max, min e.t.c for one or multiple columns. Rolling mean is
🌐
Finxter
blog.finxter.com › home › learn python blog › how to use pandas rolling – a simple illustrated guide
How to Use Pandas Rolling - A Simple Illustrated Guide - Be on the Right Side of Change
April 11, 2022 - If a BaseIndexer subclass, the window boundaries are based on the defined get_window_bounds() method. Additional rolling keywords argument, namely min_periods, center, and closed will be passed to get_window_bounds().
🌐
GitHub
github.com › pandas-dev › pandas › issues › 59252
BUG: rolling window with `center=True, min_periods=1` is not symmetric at edges · Issue #59252 · pandas-dev/pandas
July 16, 2024 - import pandas as pd import numpy as np pd.Series(np.arange(100)).rolling(21, center=True, min_periods=1).mean().plot() The np.arange gives a simple linear trend that should not be affected by the rolling mean filter. However at the edges the mean filter pulls values more towards the centre than expected, causing kinks in the curve.
Author: pandas-dev
🌐
GitHub
github.com › pandas-dev › pandas › issues › 14425
incorrect calculation of centered moving averages for even length series · Issue #14425 · pandas-dev/pandas
October 14, 2016 - Suppose the period length is 5. Then the center of 5 periods is 3. However if the period length is 4 then the center of the period is 2.5. The value at index 3 should be the average of the values at 2.5 and 3.5. Pandas is showing the 2.5 value at 3 which is incorrect. EXAMPLE: a=pd.Series(range(1,6), index=range(1,6)) a.rolling(4, center=True).mean() 1 NaN 2 NaN 3 2.5 4 3.5 5 NaN ·
Author: pandas-dev