时间序列
时间序列数据是一种非常重要的结构化数据形式,应用于:金融学、经济学、神经科学、物理学等多个领域。
- 很多时间序列是固定频率的,数据点是根据某种规律定期出现的
- 时间序列也可以是不定期的,没有固定的单位或者单位之间的偏移量
应用场景
- 时间戳
timestamp
,特定的时刻 -
pandas
通过numpy
的datatime64
数据类型以纳秒
形式存储时间戳
- 固定时期
period
- 时间间隔
interval
,由起始和结束的时间戳表示 - 时间或者时间过程
最常见的时间序列是时间戳
进行索引
日期和时间数据集工具
- 标准库:
date、time
和calendar
- 模块包含:
datetime、time、calendar
应用最多的是datetime.datetime

字符串和datetime的相互转换
- 利用str或者strftime()将datetime对象转成字符串对象:
datetime--->字符串
- datetime.strptime:将字符串转换为日期形式:
字符串---->datetime

日期的范围pd.date_range
- pandas原生序列是不规则的,没有固定频率
- pandas自带工具用于:重采样、频率判断、生成固定频率日期范围
- 生成指定的日期范围,可以指定开始和结束日期:
index = pd.date_range('2012-04-01', '2012-06-01')
pd.date_range(end='2012-06-01', periods=20)
- 生成每月的第一天或者最后一天等形式的日期格式:
pd.date_range('2000-01-01', '2000-12-01', freq='MS')
频率和移动
-
pandas中的频率通过一个基础频率
(base frequency)
和整数组成 -
基础频率通常是字符串别名,比如M表示每月,H表示每小时
-
每个基础频率都有
date offset
日期偏移量与之相对应
from pandas.tseries.offsets import Day
pd.date_range('2000-01-01', '2000-01-03 23:59', freq='4h')
-
偏移量对象能够通过加法进行相加:
Hour(2)+Minute(20)
-
传入频率字符串:
2h30min
from pandas.tseries.offsets import Hour, Minute
hour = Hour()
five_hour = Hour(5)


字符串和datetime的相互转换
- 利用
str
或者strftime()
将datetime
对象转成字符串对象:datetime--->字符串
-
datetime.strptime
:将字符串转换为日期形式:字符串---->datetime
-
datetime.strptime
:通过已知格式进行解析的最佳方式 -
dateutil
中的parser.parse
进行解析:parse("时间")



时间序列基础
- pandas中最常用的时间序列类型是时间戳
- 以字符串或者datetime对象作为索引

如何通过时间对象来选取数据
- 通过标签来选取数据
- 直接传入可以被解释为日期的字符
-
通过index标签中传入年月即可创建连续时间数据
image.png
image.png

带有重复索引的时间序列
- 通过索引的is_unique属性来判断是否唯一
-
非唯一时间戳的数据聚合:使用groupby,传入level=0
image.png
image.png
日期范围、偏移量和移动
# 日期的范围、频率和移动
# pd.date_range():生成指定频率和长度的日期对象索引
index = pd.date_range('2012-04-01', '2012-06-01')
index
# 生成指定范围,指定开始日期
pd.date_range(start='2012-04-01', periods=20)
# 指定结束日期和长度
pd.date_range(end='2012-06-01', periods=20)
# 生成每个月的最后一天,作为索引
pd.date_range('2000-01-01', '2000-12-01', freq='BM')
# 生成每个月的第一天,作为索引
pd.date_range('2000-01-01', '2000-12-01', freq='MS')
# 起始和结束日期带有时间信息;通过normalize转化为时间戳
pd.date_range('2012-05-02 12:56:31', periods=5, normalize=True)
# 偏移量处理
from pandas.tseries.offsets import Hour, Minute
hour = Hour()
five_hour = Hour(5)
Hour(2 ) + Minute(20)


WOM
- Week of Month:获取
每月第三个星期五
之类的日期
image.png
网友评论