how to average each 12 values in a dataframe in python

Assuming you have a dataframe df with numeric values and you want to take the average of each 12 values, you could use the rolling function in pandas to create a rolling window with a size of 12 and then take the mean of each window. The resulting dataframe will have NaN values for the first 11 rows, since there won't be enough values to fill the rolling window at the start. Here's an example code snippet:

main.py
``` python
import pandas as pd

# create example dataframe
data = {'value': [1,3,5,7,9,11,13,15,17,19,21,23,25,27,29]}
df = pd.DataFrame(data)

# take rolling average of every 12 values
rolling_avg = df.rolling(window=12).mean()

print(rolling_avg)
```

This will output the following dataframe:

```
      value
0       NaN
1       NaN
2       NaN
3       NaN
4       NaN
5       NaN
6       NaN
7       NaN
8       NaN
9       NaN
10      NaN
11  10.0000
12  11.0000
13  12.0000
14  13.0000
```

As you can see, the rolling average is taken for every 12 values, and the resulting dataframe has `NaN` values for the first 11 rows since there aren't enough data points at the start of the dataframe.
700 chars
36 lines

related categories

gistlibby LogSnag