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?
this is the code
JavaScript
x
16
16
1
data= pd.DataFrame(
2
[[Timestamp('2022-08-05 10:11:04'), 140, 120],
3
[Timestamp('2022-08-05 10:11:05'), 160, 155],
4
[Timestamp('2022-08-05 10:11:06'), 230, 156],
5
[Timestamp('2022-08-05 10:11:07'), 230, 155],
6
[Timestamp('2022-08-05 10:11:08'), 230, 160],
7
[Timestamp('2022-08-05 10:11:09'), 140, 130],
8
[Timestamp('2022-08-05 10:11:10'), 140, 131],
9
[Timestamp('2022-08-05 10:11:11'), 230, 170]],
10
columns=['timestamp', 'power', 'heart rate'])
11
12
m = data['power'].gt(200) #fill in power value
13
gb = (-data['timestamp'].diff(-1))[m].groupby([(~m).cumsum()).sum()
14
gb= gb.groupby((~m).cumsum()).sum()
15
gb
16
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. like this
JavaScript
1
7
1
gb = pd.DataFrame(
2
[[Timestamp('00:00:04'), 210, 145],
3
[Timestamp('00:00:15'), 250, 155],
4
[Timestamp('00:01:00'), 230, 180],
5
6
columns=['time at high intensity', ' avg power', ' avg heart rate'])
7
Advertisement
Answer
You can create helper column from by difference and then aggregate by it and another column in named aggregation in GroupBy.agg
:
JavaScript
1
13
13
1
m = data['power'].gt(200) #fill in power value
2
gb = (data.assign(new=-data['timestamp'].diff(-1))[m]
3
.groupby((~m).cumsum())
4
.agg(time_at_high_intensity=('new','sum'),
5
avg_power=('power','mean'),
6
avg_heart_rate=('heart rate','mean')))
7
8
print (gb)
9
time_at_high_intensity avg_power avg_heart_rate
10
power
11
2 0 days 00:00:03 230 157
12
4 0 days 00:00:00 230 170
13