learner learner - 2 months ago 13
Python Question

Finding the average of two consecutive rows in pandas

I am trying to find the average of two consecutive rows in each column

In[207]: df = DataFrame({"A": [9, 4, 2, 1, 4], "B": [12, 7, 5, 4,8]})
In[208]: df
Out[207]:
A B
0 9 12
1 4 7
2 2 5
3 1 4
4 4 8


The result should be:

Out[207]:
A B
0 6.5 9.5
1 1.5 4.5


If the number of elements id odd, discard the last row.

Answer

try this:

In [29]: idx = len(df) - 1 if len(df) % 2 else len(df)

In [30]: df[:idx].groupby(df.index[:idx] // 2).mean()
Out[30]:
     A    B
0  6.5  9.5
1  1.5  4.5