Home > Back-end >  Python Pandas How to calculate the average of every other row in a column
Python Pandas How to calculate the average of every other row in a column

Time:10-27

import pandas as pd

data = {'Pressure' : [100,112,114,120,123,420,123,1230,132,1,23,13,13,13,123,13,123,3,222,2303,1233,1233,1,1,30,20,40,401,10,40,12,122,1,12,333]}

df = pd.DataFrame(data)

If I had this example DF, is there an easy way to calculate the average of every other row in the column? I would like there to be an average of rows 1,3,5,7... etc and also an average of rows 2,4,6,8,10.... I was not sure what the best way to do this would be.

CodePudding user response:

We can get the mean for the even rows this way :

>>> df.iloc[::2].mean() 
Pressure    153.111111
dtype: float64

In the brackets, the syntax is : start(do nothing):stop(do nothing):step_count(2).
So for evens you'd start at 0, go to end, increment by 2.

And we can do the following for the odds rows :

>>> df.iloc[1::2].mean()
Pressure    356.294118
dtype: float64

For odds, we start at 1, go to end, increment by 2.

CodePudding user response:

Use your index to compute mean for odd and even rows as a key of groupby:

>>> df.groupby(df.index % 2).mean()
     Pressure
0  153.111111  # Rows 0, 2, 4, 6, ...
1  356.294118  # Rows 1, 3, 5, 7, ...

Note: if your index is not numeric is not a problem, create one:

>>> df.groupby(pd.RangeIndex(len(df)) % 2).mean()
     Pressure
0  153.111111
1  356.294118

CodePudding user response:

You can use iloc methods(as shown above), in that you can't get all odd/even. To overcome that issue you can use the below code(it's simply finding odd/even by doing mod of index):

j=0
even= []
odd= []
for i in df.loc[:,'Pressure']:
    if j%2 == 0:
        even.append(i)
    else:
        odd.append(i)
    j  = 1
    
print(f'Odd mean: {np.mean(odd)}')

    print(f'Even mean: {np.mean(even)}')
  • Related