Python 3.x 转换时间序列15分钟数据
我有一个时间序列数据,每15分钟取一次价格值。我想转换数据,其中每个时间块成为一列,我们得到特定日期的一行。 例如,包含2列-['Date-Time','Price']的数据帧将生成1+96列-['Date']和每个时间块的96列的数据帧 下面是我为将小时转换为列而编写的代码,其中给出了24列小时。如何将15分钟的时间转换为96列-Python 3.x 转换时间序列15分钟数据,python-3.x,pandas,time-series,python-datetime,Python 3.x,Pandas,Time Series,Python Datetime,我有一个时间序列数据,每15分钟取一次价格值。我想转换数据,其中每个时间块成为一列,我们得到特定日期的一行。 例如,包含2列-['Date-Time','Price']的数据帧将生成1+96列-['Date']和每个时间块的96列的数据帧 下面是我为将小时转换为列而编写的代码,其中给出了24列小时。如何将15分钟的时间转换为96列- def transform_to_hour_cols(series): df = pd.DataFrame() start = series.in
def transform_to_hour_cols(series):
df = pd.DataFrame()
start = series.index.min()
end = series.index.max()
df['year'] = series.index.year
df['month'] = series.index.month
df['day'] = series.index.day
df['hours'] = series.index.hour
df['loads'] = series.values
df = df.set_index(['year', 'month', 'day', 'hours'], append=True).unstack()
df = df.groupby(['year', 'month', 'day']).sum()
df.reset_index(inplace=True)
df.drop(['year', 'month', 'day'], axis=1, inplace=True)
date_list = pd.date_range(start=start, end=end, freq='D').strftime('%Y-%m-%d')
df.index = pd.DatetimeIndex(date_list, name='date')
return df
price = transform_to_hour_cols(df['Price'])
price.head()
下面是示例数据帧-
dt.date
和dt.time
创建一个date
和time
列time
发送到列。为此,首先,您必须使用将日期
和时间
放在索引上。set_index()
。然后,使用.unstack(1)
将时间移动到列中。unstack()
中的1
表示您正在传递刚刚创建的多索引中的第二个索引列。如果您已通过0
,则您将向列发送date
.reset\u index(level=0)
根据您提供的示例数据,我假设您已经成功地按日期行将15分钟间隔分组,因此这有助于将15分钟间隔分组到列中
dt.date
和dt.time
创建一个date
和time
列time
发送到列。为此,首先,您必须使用将日期
和时间
放在索引上。set_index()
。然后,使用.unstack(1)
将时间移动到列中。unstack()
中的1
表示您正在传递刚刚创建的多索引中的第二个索引列。如果您已通过0
,则您将向列发送date
.reset\u index(level=0)
根据您提供的示例数据,我假设您已经成功地按日期行将15分钟间隔分组,因此这有助于您将15分钟间隔分组到列中。您可以使用
Series.dt.minute
获得按分钟的分布。由于您的数据只有15分钟的窗口,它将自动调整相同的窗口。您可以使用Series.dt.minute
获得按分钟分布。由于您的数据只有15分钟的窗口,它将自动调整相同的时间。
df = pd.DataFrame({'date' : ['2020-04-01 00:00:00', '2020-04-01 00:15:00',
'2020-04-01 00:30:00', '2020-04-01 00:45:00', '2020-04-01 01:00:00'],
'mcp' : [2399.21, 2499.07, 2448.89, 2399.80, 2199.89]})
df['date'] = pd.to_datetime(df['date'])
df['time'] = df['date'].dt.time
df['date'] = df['date'].dt.date
df = df.set_index(['date', 'time']).unstack(1).reset_index(level=0)
df
Out[1]:
date mcp
time 00:00:00 00:15:00 00:30:00 00:45:00 01:00:00
0 2020-04-01 2399.21 2499.07 2448.89 2399.8 2199.89