简体   繁体   English

Python Pandas 如何计算列中每隔一行的平均值

[英]Python Pandas How to calculate the average of every other row in a column

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?如果我有这个示例 DF,是否有一种简单的方法来计算列中每隔一行的平均值? 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.我希望平均有 1、3、5、7 行……等等,还有平均 2、4、6、8、10 行……我不确定最好的方法是什么这将是。

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).在括号中,语法是:start(do nothing):stop(do nothing):step_count(2)。
So for evens you'd start at 0, go to end, increment by 2.所以对于偶数,你从 0 开始,到结束,增加 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.对于赔率,我们从 1 开始,到结束,增加 2。

Use your index to compute mean for odd and even rows as a key of groupby :使用您的索引计算奇数行和偶数行的平均值作为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

You can use iloc methods(as shown above), in that you can't get all odd/even.您可以使用 iloc 方法(如上所示),因为您无法获得所有奇数/偶数。 To overcome that issue you can use the below code(it's simply finding odd/even by doing mod of index):为了克服这个问题,您可以使用以下代码(它只是通过对索引进行 mod 来查找奇数/偶数):

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)}')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM