Pandas Moving Window Over Rows
Is there a way to apply a function over a moving window centered around the current row?, for example: >>> df = pd.DataFrame({'A': {0: 'a', 1: 'b', 2: 'c'}, ...
Solution 1:
It looks like you just want a rolling mean, with a centred window of 3. For example:
>>>df["D"] = pd.rolling_mean(df["C"], window=3, center=True, min_periods=2)>>>df
A B C D
0 a 1 2 3
1 b 3 4 4
2 c 5 6 5
Solution 2:
Updated answer: pd.rolling_mean
was deprecated in 0.18 and is no longer available as of pandas=0.23.4.
Window functions are now methods
Window functions have been refactored to be methods on
Series/DataFrame
objects, rather than top-level functions, which are now deprecated. This allows these window-type functions, to have a similar API to that of.groupby
.
It either needs to be called on the dataframe:
In [55]: df['D'] = df['C'].rolling(window=3, center=True, min_periods=2).mean()
In [56]: df
Out[56]:
A B C D
0 a 1 2 3.0
1 b 3 4 4.0
2 c 5 6 5.0
Or from pandas.core.window.Rolling:
In [57]: df['D'] = pd.core.window.Rolling(df['C'], window=3, center=True, min_periods=2).mean()
In [58]: df
Out[58]:
A B C D
0 a 1 2 3.0
1 b 3 4 4.0
2 c 5 6 5.0
Post a Comment for "Pandas Moving Window Over Rows"