时间序列分析是数据科学和统计分析中非常重要的一部分。在这个教程中,我们将使用 Pandas 库来处理和分析时间序列数据。
基础概念
时间序列数据是由一系列按时间顺序排列的数据点组成的。例如,股票价格、气温、销售额等都可以看作是时间序列数据。
时间序列的基本组成
- 时间戳:数据点的具体时间。
- 数据值:时间戳对应的数据点。
Pandas 中的时间序列
Pandas 库提供了丰富的工具来处理时间序列数据。
创建时间序列
import pandas as pd
# 创建一个时间序列
date_range = pd.date_range(start='2021-01-01', periods=5, freq='D')
ts = pd.Series(np.random.randn(len(date_range)), index=date_range)
print(ts)
时间序列的索引
Pandas 中的时间序列数据通常以时间戳作为索引。
print(ts.index)
时间序列的常用方法
resample()
:重采样时间序列数据。to_period()
:将时间序列转换为周期。to_timestamp()
:将时间戳转换为 Pandas 时间序列。
实例分析
假设我们有一个包含每日销售额的时间序列数据,我们可以使用 Pandas 来分析这些数据。
加载数据
sales_data = pd.read_csv('/path/to/sales_data.csv')
绘制时间序列图
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 5))
plt.plot(sales_data.index, sales_data['sales'])
plt.title('Daily Sales')
plt.xlabel('Date')
plt.ylabel('Sales')
plt.grid(True)
plt.show()
时间序列预测
Pandas 并不直接提供时间序列预测的功能,但可以与 scikit-learn 等库结合使用。
Pandas 时间序列分析示例