跳至主要內容

时间序列

blacklad大约 3 分钟PythonPythonPandas

时间序列

1 简介

时间序列 (Time Series) 是指按照时间顺序排列的一组数据点,这些数据点通常表示某个变量在不同时间点的变化。

事物的发展总是伴随着时间推进,数据指标也在各个时间点上产生。时间序列(简称“时序”​)是在一个时间周期内,测量值按照时间顺序变化,将这个变量与关联的时间对应而形成的一个数据序列

1.1 应用场景

  • 金融分析:例如股票价格随时间的变化。
  • 销售预测:通过过去的销售数据来预测未来的趋势。
  • 气候研究:分析历史气温、降水量等气候数据。

2 时间序列

2.1 创建时间序列

要创建一个时间序列,首先需要创建一个时间索引。Pandas 提供了一个 date_range 函数,可以方便地生成一个连续的时间索引。

import pandas as pd

# 创建一个时间索引
date_index = pd.date_range(start='2024-01-01', periods=5, freq='D')
# 创建一个简单的 Series
ts = pd.Series([20, 21, 22, 23, 24], index=date_index)
print(ts)
2024-01-01    20
2024-01-02    21
2024-01-03    22
2024-01-04    23
2024-01-05    24
Freq: D, dtype: int64

3 时序索引

3.1 时间索引的创建

时序索引 (DatetimeIndex) 是 Pandas 中专门用于时间序列数据的索引类型。通过 pd.to_datetime() 方法,可以将字符串或其他类型的数据转换为时间戳,创建时序索引。

一般我们读取到的数据都是字符串,需要转换为时间类型

# 将字符串转换为时间戳
date_strings = ['2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04']
datetime_index = pd.to_datetime(date_strings)

print(datetime_index)
DatetimeIndex(['2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04'], dtype='datetime64[ns]', freq=None)

3.2 时间索引的操作

import pandas as pd

# 创建一个从2024-01-01开始,每天一个时间点,共5天的时间索引
date_index = pd.date_range(start='2024-01-01', periods=5, freq='D')

# 创建一个带有时间索引的 Series
ts = pd.Series([20, 21, 22, 23, 24], index=date_index)

3.2.1 选择

使用标签选择特定时间的数据。

# 选择2024-01-02这一天的数据
print(ts['2024-01-02'])
21

3.2.2 切片选择

可以使用切片来选择一段时间内的数据。

# 选择2024-01-02到2024-01-04之间的数据
print(ts['2024-01-02':'2024-01-04'])
2024-01-02    21
2024-01-03    22
2024-01-04    23
Freq: D, dtype: int64

3.2.3 排序操作

如果数据来自不同的来源或者经过某些处理后变得无序,使用 .sort_index() 方法来重新排序

# 打乱时间索引
date_strings = ['2024-01-03', '2024-01-02', '2024-01-01', '2024-01-04', '2024-01-05']
ts_shuffled = ts.reindex(index=pd.to_datetime(date_strings))

print(ts_shuffled)
# 重新排序时间索引
sorted_ts = ts_shuffled.sort_index()

# 输出排序后的 Series
print(sorted_ts)
2024-01-03    22
2024-01-02    21
2024-01-01    20
2024-01-04    23
2024-01-05    24
dtype: int64
2024-01-01    20
2024-01-02    21
2024-01-03    22
2024-01-04    23
2024-01-05    24
dtype: int64

4 时间偏移

时间偏移 (Time Offsets) 是指对时间序列数据的索引进行日期的加减操作。

4.1 时间相加/减

通过时间加减,可以很方便地模拟未来的日期或回溯过去的日期。

# 创建一个从2024-01-01开始,每天一个时间点,共5天的时间索引
date_index = pd.date_range(start='2024-01-01', periods=5, freq='D')
date_index - pd.Timedelta(days=2)
DatetimeIndex(['2023-12-30', '2023-12-31', '2024-01-01', '2024-01-02',
               '2024-01-03'],
              dtype='datetime64[ns]', freq='D')

4.1 时间差异

diff 函数可以计算每条时间与前一条的时间差。

# 创建间隔7天的数据
date_index = pd.date_range(start='2024-01-01', periods=5, freq='W')

# 计算时间差异
time_diff = date_index.to_series().diff()
print(time_diff)
2024-01-07      NaT
2024-01-14   7 days
2024-01-21   7 days
2024-01-28   7 days
2024-02-04   7 days
Freq: W-SUN, dtype: timedelta64[ns]
上次编辑于:
贡献者: blacklad