我有以下df:
DATETIME OPEN HIGH Count
02/03/1997 09:04:00 3046.00 3048.50 20
02/03/1997 09:05:00 3047.00 3048.00 13
02/03/1997 09:06:00 3047.50 3048.00 6
02/03/1997 09:07:00 3047.50 3047.50 12
02/03/1997 09:08:00 3048.00 3048.00 136
02/03/1997 09:09:00 3048.00 3048.00 174
02/03/1997 09:10:00 3046.50 3046.50 134
02/03/1997 09:11:00 3045.50 3046.00 43
02/03/1997 09:12:00 3045.00 3045.50 214
02/03/1997 09:13:00 3045.50 3045.50 8
02/03/1997 09:14:00 3045.50 3046.00 152
我想通过5 Minute interval
、Count
的sum
和OPEN and HIGH
的mean
来group
数据帧。
我试着用下面的代码做了1分钟的集成:
首先,我使用以下函数将DATETIME列转换为天、小时、分钟:
def date_convertion(df):
df['date_time_from_epoch'] = pd.to_datetime(df['DATETIME'], format='%d-%b-%y %H.%M.%S.%f %p', errors='coerce')
df['date'] = df['date_time_from_epoch'].dt.date
df['day'] = df['date_time_from_epoch'].dt.day
df['month'] = df['date_time_from_epoch'].dt.month
df['hours']= df["date_time_from_epoch"].dt.hour
df['minute']= df["date_time_from_epoch"].dt.minute
return df
然后使用以下代码来聚合每个1分钟时间间隔的日期:
d = {'Count':['sum'],'OPEN': ['mean'],'HIGH': ['mean']}
res = merged_data.groupby(['date','day','month','hours','minute']).agg(d).reset_index()
res.columns = ['_'.join(col) for col in res.columns.values]
上面的脚本适用于1 minute aggregate
数据,但我想在5 minute
和Count(sum), OPEN(mean) and HIGH(mean)
的基础上进行聚合
使用DataFrame.resample
:
res = merged_data.resample('5Min', on='date_time_from_epoch').agg(d).reset_index()
或Grouper
:
res = merged_data.groupby(pd.Grouper(freq='5Min', key='date_time_from_epoch')).agg(d).reset_index()