Python Pandas时间序列处理:生成、转换与重采样实战
本文详解Python Pandas库中时间序列处理的核心功能。涵盖使用pd.date_range和pd.period_range生成日期序列的区别,通过pd.Timestamp和pd.to_datetime创建及转换时间戳对象,解析Period对象的时间间隔计算,以及利用asfreq和resample进行频率转换与数据重采样统计。
Pandas时间序列处理概述
前言
在利用Python开展数据分析工作时,时间日期的格式处理与转换是高频需求,尤其是在挖掘与时间维度相关的数据场景下,例如量化交易中通过历史数据探索股价波动规律。Python内置的datetime模块及NumPy库均提供了基础的时间处理手段,而Pandas作为Python生态中强大的数据分析库,更是内置了完善的时间序列处理功能,成为处理时间序列数据的理想工具。
日期序列的生成方法
1、生成日期序列
Pandas主要提供pd.date_range()和pd.period_range()两个函数来生成日期序列。这两个函数支持设置起始时间、结束时间、生成时期的数量以及时间频率(freq参数,如'M'代表月,'D'代表天,'W'代表周,'Y'代表年)等关键参数。
两者的核心区别在于返回的数据结构类型:pd.date_range()生成的是DatetimeIndex格式的日期序列,而pd.period_range()生成的是PeriodIndex格式的日期序列。
下面通过生成月度时间序列和周度时间序列的代码示例进行对比说明:
date_rng = pd.date_range('2019-01-01', freq='M', periods=12)
print(f'month date_range():
{date_rng}')
"""
date_range():
DatetimeIndex(['2019-01-31', '2019-02-28', '2019-03-31', '2019-04-30',
'2019-05-31', '2019-06-30', '2019-07-31', '2019-08-31',
'2019-09-30', '2019-10-31', '2019-11-30', '2019-12-31'],
dtype='datetime64[ns]', freq='M')
"""
period_rng = pd.period_range('2019/01/01', freq='M', periods=12)
print(f'month period_range():
{period_rng}')
"""
period_range():
PeriodIndex(['2019-01', '2019-02', '2019-03', '2019-04', '2019-05', '2019-06',
'2019-07', '2019-08', '2019-09', '2019-10', '2019-11', '2019-12'],
dtype='period[M]', freq='M')
"""
date_rng = pd.date_range('2019-01-01', freq='W-SUN', periods=12)
print(f'week date_range():
{date_rng}')
"""
week date_range():
DatetimeIndex(['2019-01-06', '2019-01-13', '2019-01-20', '2019-01-27',
'2019-02-03', '2019-02-10', '2019-02-17', '2019-02-24',
'2019-03-03', '2019-03-10', '2019-03-17', '2019-03-24'],
dtype='datetime64[ns]', freq='W-SUN')
"""
period_rng=pd.period_range('2019-01-01',freq='W-SUN',periods=12)
print(f'week period_range():
{period_rng}')
"""
week period_range():
PeriodIndex(['2018-12-31/2019-01-06', '2019-01-07/2019-01-13',
'2019-01-14/2019-01-20', '2019-01-21/2019-01-27',
'2019-01-28/2019-02-03', '2019-02-04/2019-02-10',
'2019-02-11/2019-02-17', '2019-02-18/2019-02-24',
'2019-02-25/2019-03-03', '2019-03-04/2019-03-10',
'2019-03-11/2019-03-17', '2019-03-18/2019-03-24'],
dtype='period[W-SUN]', freq='W-SUN')
"""
date_rng = pd.date_range('2019-01-01 00:00:00', freq='H', periods=12)
print(f'hour date_range():
{date_rng}')
"""
hour date_range():
DatetimeIndex(['2019-01-01 00:00:00', '2019-01-01 01:00:00',
'2019-01-01 02:00:00', '2019-01-01 03:00:00',
'2019-01-01 04:00:00', '2019-01-01 05:00:00',
'2019-01-01 06:00:00', '2019-01-01 07:00:00',
'2019-01-01 08:00:00', '2019-01-01 09:00:00',
'2019-01-01 10:00:00', '2019-01-01 11:00:00'],
dtype='datetime64[ns]', freq='H')
"""
period_rng=pd.period_range('2019-01-01 00:00:00',freq='H',periods=12)
print(f'hour period_range():
{period_rng}')
"""
hour period_range():
PeriodIndex(['2019-01-01 00:00', '2019-01-01 01:00', '2019-01-01 02:00',
'2019-01-01 03:00', '2019-01-01 04:00', '2019-01-01 05:00',
'2019-01-01 06:00', '2019-01-01 07:00', '2019-01-01 08:00',
'2019-01-01 09:00', '2019-01-01 10:00', '2019-01-01 11:00'],
dtype='period[H]', freq='H')
"""
时间戳对象的创建与转换
2、生成Timestamp对象及转换
创建Timestamp时间戳对象主要有pd.Timestamp()和pd.to_datetime()两种方法。具体用法及类型转换示例如下:
ts=pd.Timestamp(2019,1,1)
print(f'pd.Timestamp()-1:{ts}')
#pd.Timestamp()-1:2019-01-01 00:00:00
ts=pd.Timestamp(dt(2019,1,1,hour=0,minute=1,second=1))
print(f'pd.Timestamp()-2:{ts}')
#pd.Timestamp()-2:2019-01-01 00:01:01
ts=pd.Timestamp("2019-1-1 0:1:1")
print(f'pd.Timestamp()-3:{ts}')
#pd.Timestamp()-3:2019-01-01 00:01:01
print(f'pd.Timestamp()-type:{type(ts)}')
#pd.Timestamp()-type:<class 'pandas._libs.tslibs.timestamps.Timestamp'>
#dt=pd.to_datetime(2019,1,1) 不支持
dt=pd.to_datetime(dt(2019,1,1,hour=0,minute=1,second=1))
print(f'pd.to_datetime()-1:{dt}')
#pd.to_datetime()-1:2019-01-01 00:01:01
dt=pd.to_datetime("2019-1-1 0:1:1")
print(f'pd.to_datetime()-2:{dt}')
#pd.to_datetime()-2:2019-01-01 00:01:01
print(f'pd.to_datetime()-type:{type(dt)}')
#pd.to_datetime()-type:<class 'pandas._libs.tslibs.timestamps.Timestamp'>
#pd.to_datetime生成自定义时间序列
dtlist=pd.to_datetime(["2019-1-1 0:1:1", "2019-3-1 0:1:1"])
print(f'pd.to_datetime()-list:{dtlist}')
#pd.to_datetime()-list:DatetimeIndex(['2019-01-01 00:01:01', '2019-03-01 00:01:01'], dtype='datetime64[ns]', freq=None)
#时间戳转换为period月时期
pr = ts.to_period('M')
print(f'ts.to_period():{pr}')
#ts.to_period():2019-01
print(f'pd.to_period()-type:{type(pr)}')
#pd.to_period()-type:<class 'pandas._libs.tslibs.period.Period'>
Period对象与时间间隔处理
3、生成period对象及转换
#定义时期period
per=pd.Period('2019')
print(f'pd.Period():{per}')
#pd.Period():2019
per_del=pd.Period('2019')-pd.Period('2018')
print(f'2019和2018间隔{per_del}年')#可以直接+、-整数(代表年)
#2019和2018间隔1年
#时期转换为时间戳
print(per.to_timestamp(how='end'))#2019-12-31 00:00:00
print(per.to_timestamp(how='start'))#2019-01-01 00:00:00
4、生成时间间隔Timedelta
#生成时间间隔Timedelta
print(pd.Timedelta(days=5, minutes=50, seconds=20, milliseconds=10, microseconds=10, nanoseconds=10))
#5 days 00:50:20.010010
#获取当前时间
now=pd.datetime.now()
#计算当前时间往后50天的日期
dt=now+pd.Timedelta(days=50)
print(f'当前时间是{now}, 50天后时间是{dt}')
#当前时间是2019-06-08 17:59:31.726065, 50天后时间是2019-07-28 17:59:31.726065
#只显示年月日
print(dt.strftime('%Y-%m-%d'))#2019-07-28
频率转换与数据重采样
5、重采样及频率转换
#asfreq 按季度显示索引值
#'DatetimeIndex' object has no attribute 'asfreq'
date=pd.date_range('1/1/2018', periods=20, freq='D')
tsdat_series=pd.Series(range(20),index=date)
tsp_series=tsdat_series.to_period('D')
print(tsp_series.index.asfreq('Q'))
date=pd.period_range('1/1/2018', periods=20, freq='D')
tsper_series=pd.Series(range(20),index=date)
print(tsper_series.index.asfreq('Q'))
"""
PeriodIndex(['2018Q1', '2018Q1', '2018Q1', '2018Q1', '2018Q1', '2018Q1',
'2018Q1', '2018Q1', '2018Q1', '2018Q1', '2018Q1', '2018Q1',
'2018Q1', '2018Q1', '2018Q1', '2018Q1', '2018Q1', '2018Q1',
'2018Q1', '2018Q1'],
dtype='period[Q-DEC]', freq='Q-DEC')
"""
#resample 按季度统计并显示
print(tsdat_series.resample('Q').sum().to_period('Q'))
"""
2018Q1 190
Freq: Q-DEC, dtype: int64
"""
#groupby 按周进行汇总求平均值
print(tsdat_series.groupby(lambda x:x.weekday).mean())
"""
0 7.0
1 8.0
2 9.0
3 10.0
4 11.0
5 12.0
6 9.5
dtype: float64
"""
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













