文章目录
基于Python的数学建模
- Github仓库:Mathematical-modeling
时间序列处理
datatime数据转换
- Python内置datetime模块提供了各种日期和时间对象。
- Pandas可以将datatime对象转换为Timestamp时间戳对象便于进一步处理
- Timeseries以及创建了大量用于操作时间序列数据的新功能。
import pandas as pd
import datetime
import numpy as np
# 将datetime转换为Timestamp对象
timestamp = pd.to_datetime('20220128')
print(timestamp)
# pd.to_datetime可以接受不同类型的datetime对象
# 多个datetime对象将被将被转换为DatetimeIndex类
Date_Index = pd.to_datetime(
['20220125', '26/01/2022', np.datetime64('2022-02-25'), datetime.datetime(2022, 2, 26)])
print(Date_Index)
- 创建以时间戳为索引的DataFrame/Series对象
data_dataframe = pd.DataFrame(
[[5, 3], [10, 5], [15, 7], [20, 9]], index=Date_Index)
print(data_dataframe)
print('-------')
data_series = pd.Series([5, 10, 15, 20], index=Date_Index)
print(data_series)
时间序列索引
位置索引
print(data_dataframe.iloc[2,:])
print(data_series[2])
时间戳(index)索引
- 符合被解析的日期格式可以直接输入
print(data_dataframe.loc['2022-01-25'])
print(data_dataframe.loc['20220125'])
print(data_dataframe.loc['2022.01.25'])
print(data_dataframe.loc['2022/01/25'])
print(data_series['20220125'])
- 可以用指定年或月份操作索引数据
print(data_dataframe.loc['2022'])
print(data_dataframe.loc['2022-01'])
truncate()方法截取
# 对数据进行重新排序
data_dataframe = data_dataframe.sort_index()
# 截取指定时间段的数据
print(data_dataframe.truncate(before='2022-02-1', after=None, axis=0, copy=True))
print(data_dataframe.truncate(before=None, after='2022-02-1', axis=0, copy=True))
创建时间序列
创建固定频率的时间序列
- DatetimeIndex是用来创建一系列时间点的一种pandas结构
datetime_index = pd.date_range(start='2022/01/01', end='2022/02/28',periods=7)
datetime_index
datetime_index = pd.date_range(start='2022/01/01', end='2022/02/28',freq='B')
datetime_index
指定时间序列频率与偏移量
pandas.tseries.offsets
模块
from pandas.tseries.offsets import *
# 生成日期偏移量
date_offset = Week(1) + Hour(7)
pd.date_range('2022/1/1', '2022/1/31', freq=date_offset)
创建标准的时间段或时期
- PeriodIndex是用来创建一系列时间段的pandas结构
# 创建Period对象,表示从2022-01-01到2022-12-31之间的时间段
period = pd.Period('2017/6')
period
# 表示从2022-01-01到2022-01-30之间的整月时间
period = pd.Period('2022/1')
period
- Period对象可进行数学运算
period + 1 # Period对象加上一个整数
- 创建多个Period对象
period_index = pd.period_range('2022-01-01', '2022-06-30', freq='M')
period_index
- 时间频率转换
period = pd.Period('2022', freq='A-DEC')
period.asfreq('M', how='start')
### 时间序列的移动
date_index = pd.date_range('2022/01/01', periods=5)
time_series = pd.Series(np.arange(5) + 1, index=date_index)
print(time_series)
print('------------')
# 向后移动一次
print(time_series.shift(1))
print('------------')
# 向前移动一次
print(time_series.shift(-1))
时间序列重采样
重采样(Resample)
resample(rule, how=None, axis=0, fill_method=None, closed=None, label=None, ...)
date_index = pd.date_range('2022-01-01', periods=30)
time_series = pd.Series(np.arange(30), index=date_index)
time_series
time_series.resample('W-MON').mean()
降采样
- 降采样时间颗粒会变大,数据量是减少的。为了避免有些时间戳对应的数据闲置,可以利用内置方法聚合数据。
date_index = pd.date_range('2022/01/01', periods=30)
shares_data = np.random.rand(30)
time_ser = pd.Series(shares_data, index=date_index)
time_ser
time_ser.resample('7D').ohlc() # OHLC重采样
升采样
- 升采样的时间颗粒是变小的,数据量会增多,这很有可能导致某些时间戳没有相应的数据
- 常用的解决办法为插值
data_demo = np.array([['101', '210', '150'], ['330', '460', '580']])
date_index = pd.date_range('2018/06/10', periods=2, freq='W-SUN')
time_df = pd.DataFrame(data_demo, index=date_index,
columns=['A产品', 'B产品', 'C产品'])
time_df
time_df.resample('D').asfreq()
time_df.resample('D').ffill()
滑动窗口
- 根据指定的单位长度来框住时间序列,从而计算框内的统计指标。
- 移动窗口就是窗口向一端滑行,每次滑行并不是区间整块的滑行,而是一个单位一个单位的滑行。
- Pandas中窗口方法
rolling()
year_data = np.random.randn(365)
date_index = pd.date_range('2017-01-01', '2017-12-31', freq='D')
ser = pd.Series(year_data, date_index)
ser.head()
roll_window = ser.rolling(window=10)
roll_window
roll_window.mean()
import matplotlib.pyplot as plt
plt.plot(ser, '--')
ser_window = ser.rolling(window=10).mean()
plt.plot(ser_window)