Adrian
Adrian

Reputation: 784

Pandas: Calculate the average every 2 rows of a column and put it into the a new column

I want to make an average of a column, but I want the averages to be put into a new column with pandas.

I want to go from this format:

values
10
5
8
7
2
5
6
7

To this format:

values  average
10  nan
5   7.5
8   6.5
7   7.5
2   4.5
5   3.5
6   5.5
7   6.5

There is a solution for something similar here: Averaging every two consecutive index values(every 2min) in pandas dataframe, but I want to keep the same number of rows.

Upvotes: 4

Views: 2881

Answers (2)

Adrian
Adrian

Reputation: 784

In the other solution, the values are replacing the column in question. I want to put them into a new column. In the meantime, I manage to come up with a solution thanks to Paul H:

df = pd.DataFrame({'values': [10, 5, 8, 7, 2, 5, 6, 7]})
df["average"] = df["values"].rolling(2).mean()
print(df)

Output:

   values  average
0      10      NaN
1       5      7.5
2       8      6.5
3       7      7.5
4       2      4.5
5       5      3.5
6       6      5.5
7       7      6.5

Upvotes: 2

mrzo
mrzo

Reputation: 2135

You can use pd.Series.rolling for that (https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rolling.html):

data = pd.Series([10, 5, 8, 7, 2, 5, 6, 7])
print(data.rolling(2).mean())

Output:

0    NaN
1    7.5
2    6.5
3    7.5
4    4.5
5    3.5
6    5.5
7    6.5
dtype: float64

Upvotes: 5

Related Questions