Python数据分析:pandas时间序列处理及操作
基本类型,以时间戳为索引的series–>datatimeindex
创建方法:
- 指定index为datatime的list
from datetime import datetime
import pandas as pd
import numpy as np
# 指定index为datetime的list
date_list = [datetime(2019, 2, 18), datetime(2019, 2, 19),
datetime(2019, 2, 25), datetime(2019, 2, 26),
datetime(2019, 4, 4), datetime(2019, 4, 5)]
time_s = pd.Series(np.random.randn(6), index=date_list)
print(time_s)
print(type(time_s.index))
运行:
- pd.date_range()
# pd.date_range()
dates = pd.date_range('2019-02-18', # 起始日期
periods=5, # 周期
freq='W-SAT') # 频率
print(dates)
print(pd.Series(np.random.randn(5), index=dates))
运行:
运算时按时间索引对齐
索引
- 索引位置
# 索引位置
print(time_s[0])
运行:
- 索引值
# 索引值
print(time_s[datetime(2019, 2, 18)])
运行:
- 可以被解析的日期字符串
# 可以被解析的日期字符串
print(time_s['2019/02/18'])
运行:
- 按年份、月份索引
# 按“年份”、“月份”索引
print(time_s['2019-2'])
运行:
- 切片操作
# 切片操作
print(time_s['2019-2-26':])
运行:
过滤 truncate
time_s.truncate(before='2019-2-25')
运行:
生成日期范围pd.data_range()
- 传入开始、结束日期,默认生成的该时间段的时间点是按天计算(频率是D)
# 传入开始、结束日期,默认生成的该时间段的时间点是按天计算的
date_index = pd.date_range('2019/02/18', '2019/03/18')
print(date_index)
运行:
- 只传入开始或结束日期,还需要传入时间段
# 只传入开始或结束日期,还需要传入时间段
print(pd.date_range(start='2019/02/18', periods=10))
运行:
- 规范化时间戳 normalize=True
# 规范化时间戳
print(pd.date_range(start='2019/02/18 12:13:14', periods=10))
print(pd.date_range(start='2019/02/18 12:13:14', periods=10, normalize=True))
运行:
- 频率Freq 由基础频率的倍数组成,基础频率包括:
- BM:business end of month,每个月最后一个工作日
- D:天,M:月
print(pd.date_range('2019/02/18', '2019/03/18', freq='2D'))
运行:
- 偏移量,每个基础频率对应一个偏移量
- 偏移量通过加法连接
# 偏移量通过加法连接
sum_offset = pd.tseries.offsets.Week(2) + pd.tseries.offsets.Hour(12)
print(sum_offset)
print(pd.date_range('2019/02/18', '2019/03/18', freq=sum_offset))
运行:
- 移动数据(shifting),沿时间轴将数据前移或后移,保持索引不变
ts = pd.Series(np.random.randn(5), index=pd.date_range('20190218', periods=5, freq='W-SAT'))
print(ts)
print('------------')
print(ts.shift(1))
运行:
时间周期计算
- period类,通过字符串或整数及基础频率构造
- period对象可进行数学运算,但要保证具有相同的基础频率
- period_range,创建指定规则的时间周期范围,生成periodindex索引,可用于创建series或dataframe
- 时间周期的频率转换, asfreq
- 按季度计算时间周期频率