# Rolling mean & roll-rotate

Rolling mean is when we average the values in a given dimension by sliding a window.

```from collections import OrderedDict from pandas import DataFrame, rolling_mean size_moving_window = 5 celsius_temps = ( ('January', (2, 5, 8, 5, 6, 8, 4, 4, 7, 4)), ('February', (6, 12, 8, 10, 8, 8, 10, 10, 9, 9)), ('March', (9, 9, 11, 13, 14, 10, 7, 9, 13, 11)), ('April', (12, 14, 15, 17, 11, 13, 11, 14, 16, 9)), ('May', (14, 16, 19, 16, 14, 15, 11, 14, 16, 18)) ) od = OrderedDict() for mon, temps in celsius_temps: od[mon] = temps df = DataFrame(od) rolling_mean_df = DataFrame.rolling(df, size_moving_window).mean().dropna() for month in rolling_mean_df: print(month, rolling_mean_df[month].tolist()) """ January [5.2, 6.4, 6.2, 5.4, 5.8, 5.4] February [8.8, 9.2, 8.8, 9.2, 9.0, 9.2] March [11.2, 11.4, 11.0, 10.6, 10.6, 10.0] April [13.8, 14.0, 13.4, 13.2, 13.0, 12.6] May [15.8, 16.0, 15.0, 14.0, 14.0, 14.8] """```

The window is aligned to the right by default; the last 5.4 value for January comes from (8+4+4+7+4) / 5. When the left side of the moving window exceeds the left boundary on the list, the values become nan, but we can remove these with the "dropna" function.

Roll and rotate allow us to manipulate matrix values in less obvious ways. If you have used the deque from the collections module, you probably know about its rotate function. Roll can perform similarly, except that we don't have a single-dimensional list, but a two-dimensional matrix of values.

```import numpy as np A = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16] ] A = np.roll(A, 1) print(A) """ [[16 1 2 3] [ 4 5 6 7] [ 8 9 10 11] [12 13 14 15]] """ A = np.roll(A, 1, axis=0) print(A) """ [[12 13 14 15] [16 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] """ A = np.roll(A, 2, axis=1) print(A) """ [[14 15 12 13] [ 2 3 16 1] [ 6 7 4 5] [10 11 8 9]] """```

Rotate, as its name says, rotates a matrix by 90 degrees, where we can specify multiples of that and the rotation orientation (clockwise or counterclockwise).

```A = np.rot90(A) print(A) """ [[13 1 5 9] [12 16 4 8] [15 3 7 11] [14 2 6 10]] """ A = np.rot90(A, -1) print(A) """ [[14 15 12 13] [ 2 3 16 1] [ 6 7 4 5] [10 11 8 9]] """ A = np.rot90(A, 2) print(A) """ [[ 9 8 11 10] [ 5 4 7 6] [ 1 16 3 2] [13 12 15 14]] """```

Roll and rotate can be combined for some interesting effects.