Ну, этот код предполагает, что у вас есть фрейм данных df
с индексом datetime datatime_col
и двумя столбцами t1
и t2
:
mean_1 = {}
mean_2 = {}
for i in range(0,24):
# If you have performance issues, you can enhance this conditions with numpy arrays
j = i+1
if (i < 10):
i = '0'+str(i)
if (j < 10):
j = '0'+str(j)
if (j == 24):
j = '00'
row_first = df.between_time(f'{i}:06:00',f'{i}:35:00').reset_index().resample('D', on='datetime_col').mean().reset_index()
row_last = df.between_time(f'{i}:36:00',f'{j}:05:00').reset_index().resample('D', on='datetime_col').mean().reset_index()
#This just confirm that you have rows in those times
if len(row_first) != 0 and len(row_last) != 0:
# By default, pandas mean return a float with lot of decimal values,
# Then, you can apply round() or int
if j == '00':
mean_1[str((row_first.datetime_col[0].date() + pd.DateOffset(1)).date()) + f' {j}:05:00'] = [row_first.t1[0]] # [round(row_first.t1[0],1)]
mean_2[str((row_last.datetime_col[0].date() + pd.DateOffset(1)).date()) + f' {j}:05:00'] = [row_last.t2[0]] # [round(row_first.t2[0],1)]
else:
mean_1[str(row_first.datetime_col[0].date()) + f' {j}:05:00'] = [row_first.t1[0]] # [round(row_first.t1[0],1)]
mean_2[str(row_last.datetime_col[0].date()) + f' {j}:05:00'] = [row_last.t2[0]] # [round(row_first.t2[0],1)]
df_mean1 = pd.DataFrame.from_dict(mean_1, orient='index', columns=['mean_1']).reset_index().rename(columns={'index':'datetime_col'})
df_mean2 = pd.DataFrame.from_dict(mean_2, orient='index', columns=['mean_2']).reset_index().rename(columns={'index':'datetime_col'})
df_mean1['datetime_col'] = pd.to_datetime(df_mean1['datetime_col'])
df_mean2['datetime_col'] = pd.to_datetime(df_mean2['datetime_col'])
df = df.merge(df_mean1, on = 'datetime_col', how='left')
df = df.merge(df_mean2, on = 'datetime_col', how='left')