3

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.

MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419
learner
  • 2,582
  • 9
  • 43
  • 54

1 Answers1

5

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
MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419