Given a dataframe, I need to find the sum of elements in the column 'data' where the rows having local time in between the local_time and the end_time. The end_time is always local_time + 30 seconds.
Also, if the aggregated value is greater than or equal to 4 then I need to update the flags of the rows having 'local time'<=local time<='end_time' to 1, grouping by the ID column.
Input:
ID local_time end_time data Flag
0 aa 2022-01-02 10:01:06 2022-01-02 10:01:36 0 0
1 aa 2022-01-02 10:01:12 2022-01-02 10:01:42 0 0
2 aa 2022-01-02 10:01:18 2022-01-02 10:01:48 1 0
3 aa 2022-01-02 10:01:24 2022-01-02 10:01:54 1 0
4 aa 2022-01-02 10:01:30 2022-01-02 10:02:00 1 0
5 aa 2022-01-02 10:01:36 2022-01-02 10:02:06 1 0
6 aa 2022-01-02 10:01:42 2022-01-02 10:02:12 1 0
7 aa 2022-01-02 10:01:48 2022-01-02 10:02:18 0 0
8 aa 2022-01-02 10:01:54 2022-01-02 10:02:24 1 0
9 aa 2022-01-02 10:02:00 2022-01-02 10:02:30 0 0
10 aa 2022-01-02 10:02:06 2022-01-02 10:02:36 0 0
Output:
Agg Flag_new
0 4 1
1 5 1
2 5 1
3 5 1
4 4 1
5 3 1
6 2 1
7 1 1
8 1 1
9 0 1
10 0 0
Below code does the job, but it takes too much time:
aggr_data_sum = []
df['flag'] = 0
for i in range(len(df)):
id = df['ID'].iloc[i]
st_time = df['local_time'].iloc[i]
end_time = df['end_time'].iloc[i]
temp = df.loc[(df['ID'] == id) & (df['local_time'] >= st_time) & (df['local_time'] <= end_time)]
select_indices = list(temp.index)
aggr_sum=sum(temp['data'])
aggr_data_sum.append(aggr_sum)
if aggr_sum>=4:
df.loc[select_indices,'flag']=1
df['aggr_data_sum']= aggr_data_sum
df[['aggr_data_sum','flag']]