Python Pandas 时间序列处理核心功能指南
本文详解Python Pandas库中处理时间序列的核心函数。重点解析pd.date_range()生成时间索引的参数配置,包括start、end、freq等;介绍pd.to_datetime()将字符串转换为时间戳的方法;并演示如何利用DateOffset进行灵活的时间加减运算,涵盖天、月、年及组合偏移量的实际应用。
使用pd.date_range()生成时间序列
创建时间序列
函数pd.date_range()
利用指定的时间范围,该函数可以生成一个DatetimeIndex类型的时间序列索引,其中每个元素的类型均为Timestamp。这是Pandas中最常用的时间序列生成方法之一。
ts = pd.date_range('2017-09-01', periods=10, freq='d', normalize=False)
ts
输出结果为:
DatetimeIndex(['2017-09-01', '2017-09-02', '2017-09-03', '2017-09-04',
'2017-09-05', '2017-09-06', '2017-09-07', '2017-09-08',
'2017-09-09', '2017-09-10'],
dtype='datetime64[ns]', freq='D'
主要输入参数的详细解析如下:
- start:指定起始时刻,支持字符串或datetime类型,默认为None。
- end:指定结束时刻,同样支持字符串或datetime类型。若已指定periods参数,则可不设置此项,默认为None。
- periods:指定时间序列的长度,类型为整型。若已指定end参数,则可不设置此项,默认为None。
- freq:指定生成时间序列的频率,即相邻两个时间点之间的间隔。支持字符串或DateOffset类型,默认为'D'(天粒度),具体表现见上述代码输出示例。
- tz:指定时区,类型为字符串,默认为None。
- normalize:布尔类型参数,该参数在实际使用中较少见,具体功能需参考官方文档。
- name:用于设置生成的时间序列名称,类型为字符串,默认为None。
- closed:指定是否包含起始和结束边界值,默认为None,表示两端均保留。
其中,freq参数的取值可参考以下符号表示的时间间隔,支持符号与数字结合使用,例如'3d'表示每隔三天生成一个时间点。频率字符串的大小写不敏感。
B business day frequency
C custom business day frequency (experimental)
D calendar day frequency
W weekly frequency
M month end frequency
SM semi-month end frequency (15th and end of month)
BM business month end frequency
CBM custom business month end frequency
MS month start frequency
SMS semi-month start frequency (1st and 15th)
BMS business month start frequency
CBMS custom business month start frequency
Q quarter end frequency
BQ business quarter endfrequency
QS quarter start frequency
BQS business quarter start frequency
A year end frequency
BA business year end frequency
AS year start frequency
BAS business year start frequency
BH business hour frequency
H hourly frequency
T, min minutely frequency
S secondly frequency
L, ms milliseconds
U, us microseconds
N nanoseconds
利用pd.to_datetime()转换字符串
字符串转换为时间戳
使用pd.to_datetime()函数可以将表示时间的字符串转换为Timestamp对象。
pd.to_datetime('2017-09-01')
输出结果为:
Timestamp('2017-09-01 00:00:00')
常用的参数说明:
format:用于指定字符串的格式,默认情况下如上述示例所示。
基于DateOffset进行时间加减运算
时间戳的加减运算 有时需要对时间进行增加或减少操作,可以使用DateOffset类型来实现。
pd.to_datetime('2017-09-01') + pd.DateOffset(days=10)
输出结果为:
Timestamp('2017-09-11 00:00:00')
DateOffset常用的参数包括:
- months:用于设置月数的偏移。
- days:用于设置天数的偏移。
- years:用于设置年数的偏移。
- hours:用于设置小时数的偏移。
- minutes:用于设置分钟数的偏移。
- seconds:用于设置秒数的偏移。
上述参数可以同时设置,支持组合使用以实现复杂的时间偏移需求。
pd.to_datetime('2017-09-01') + pd.DateOffset(seconds=10, days = 10)
输出结果为:
Timestamp('2017-09-11 00:00:10')
以上即为本文关于Pandas时间序列处理的主要内容,希望能为读者提供有益的帮助,欢迎继续支持本站获取更多信息。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













