时间序列
文章目录
pandas时间序列
- time series
- 结构化数据形式
- 时间戳,timestamp,特定的时刻
- 固定时期,period
- 时间间隔,interval
时间序列基础
DatetimeIndex
-
pandas中的datetime对象
-
ts = pd.Series(np.random.randn(6), index=pd.date_range('2018/11/11',period=6)) ts.index # DatetimeIndex,时间戳 ts.index.dtype # 用Numpy的datetime64数据类型以 纳秒 形式存储时间戳 ts.index[0] # Timestamp
对Series的操作
-
索引
ts['2018/11/11'] ts['20181111'] ts['2018'] ts['2018/11']
-
切片
ts[datetime(2018,11,11):] ts['2018/11/11':'2019/11/11'] # 用不存在与该时间序列中的时间戳切片
-
过滤
ts.truncate(after='2018/11/12')
对DataFrame的操作
-
对DataFrame的操作
df.loc['2018/11']
-
对非唯一时间戳聚合
df.index.is_unique # 属性判断索引是否唯一 df.groupby(level=0).mean()
重采样
-
resampling
- 将时间序列从一个频率转换到另一个频率的处理过程
- 高频率 聚合 低频率——降采样(downsampling)
- 升采样(upsampling):低频率数据 转换到 高频率
- 并不是所有的重采样,都被划分为这两大类
- W-WED(每周三)转换为W-FRI,既不是降采样也不是升采样
ts.resample('D') #字符串‘D’是每天的意思 ts.resample('M',kind='period').mean()
- 将时间序列从一个频率转换到另一个频率的处理过程
resample方法的参数
-
ts.resample(freq=, # 重采样频率的字符串 axis=, # 重采样的轴,默认axis=0 fill_method=, # 升采样如何插值:‘ffill’,‘bfil