简体   繁体   English

groupby 有差异 function

[英]groupby with diff function

I have a groupby with a diff function, however I want to add an extra mean column for heart rate, how can I do this the best way?我有一个带有差异 function 的 groupby,但是我想为心率添加一个额外的平均列,我该如何以最好的方式做到这一点?

this is the code这是代码


data= pd.DataFrame(
    [[Timestamp('2022-08-05 10:11:04'), 140, 120],
    [Timestamp('2022-08-05 10:11:05'), 160, 155],
    [Timestamp('2022-08-05 10:11:06'), 230, 156],
    [Timestamp('2022-08-05 10:11:07'), 230, 155],
    [Timestamp('2022-08-05 10:11:08'), 230, 160],
    [Timestamp('2022-08-05 10:11:09'), 140, 130],
    [Timestamp('2022-08-05 10:11:10'), 140, 131],
    [Timestamp('2022-08-05 10:11:11'), 230, 170]],
    columns=['timestamp', 'power', 'heart rate'])

m = data['power'].gt(200) #fill in power value
gb = (-data['timestamp'].diff(-1))[m].groupby([(~m).cumsum()).sum()
gb= gb.groupby((~m).cumsum()).sum()
gb

where should I add in the piece of code to calculate the average heart rate?我应该在哪里添加代码来计算平均心率?

output will be the amount of seconds in high power zone and then i would like to add the average heart rate during this period. output 将是高功率区域的秒数,然后我想添加此期间的平均心率。 like this像这样

gb = pd.DataFrame(
    [[Timestamp('00:00:04'), 210, 145],
    [Timestamp('00:00:15'), 250, 155],
    [Timestamp('00:01:00'), 230, 180],
   
    columns=['time at high intensity', ' avg power', ' avg heart rate'])

You can create helper column from by difference and then aggregate by it and another column in named aggregation in GroupBy.agg :您可以根据差异创建帮助列,然后通过它和GroupBy.agg中命名聚合中的另一列进行聚合:

m = data['power'].gt(200) #fill in power value
gb = (data.assign(new=-data['timestamp'].diff(-1))[m]
          .groupby((~m).cumsum())
          .agg(time_at_high_intensity=('new','sum'),
               avg_power=('power','mean'), 
               avg_heart_rate=('heart rate','mean')))
                                               
print (gb)
      time_at_high_intensity  avg_power  avg_heart_rate
power                                                  
2            0 days 00:00:03        230             157
4            0 days 00:00:00        230             170

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

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