Python pandas 时序统计的高级用法

更多资料获取

📚 个人网站:ipengtao.com


在数据分析和处理过程中,时间序列数据(时序数据)是非常常见且重要的一类数据。Python的pandas库提供了强大的功能来处理和分析时序数据。本文将详细介绍pandas时序统计的高级用法,涵盖数据加载与预处理、时间索引与切片、重采样与窗口函数、缺失值处理以及时序数据的可视化等内容,帮助更高效地进行时序数据分析。

数据加载与预处理

示例数据

使用一个简单的股票价格数据集作为示例数据。假设数据包含日期、开盘价、最高价、最低价、收盘价和交易量。

import pandas as pd

# 示例数据
data = {
    'Date': ['2022-01-01', '2022-01-02', '2022-01-03', '2022-01-04', '2022-01-05'],
    'Open': [100, 102, 104, 106, 108],
    'High': [110, 112, 114, 116, 118],
    'Low': [95, 97, 99, 101, 103],
    'Close': [105, 107, 109, 111, 113],
    'Volume': [1000, 1500, 2000, 2500, 3000]
}
df = pd.DataFrame(data)

# 将Date列转换为datetime类型并设置为索引
df['Date'] = pd.to_datetime(df['Date'])
df.set_index('Date', inplace=True)
print(df)

输出:

            Open  High  Low  Close  Volume
Date                                        
2022-01-01   100   110   95    105    1000
2022-01-02   102   112   97    107    1500
2022-01-03   104   114   99    109    2000
2022-01-04   106   116  101    111    2500
2022-01-05   108   118  103    113    3000

时间索引与切片

时间索引与切片是时序数据处理的基础操作。pandas提供了丰富的功能来处理这些操作。

按日期范围选择数据

# 选择特定日期范围的数据
df_subset = df['2022-01-02':'2022-01-04']
print(df_subset)

输出:

            Open  High  Low  Close  Volume
Date                                        
2022-01-02   102   112   97    107    1500
2022-01-03   104   114   99    109    2000
2022-01-04   106   116  101    111    2500

按年、月、日选择数据

# 选择2022年的数据
df_2022 = df['2022']
print(df_2022)

输出:

            Open  High  Low  Close  Volume
Date                                        
2022-01-01   100   110   95    105    1000
2022-01-02   102   112   97    107    1500
2022-01-03   104   114   99    109    2000
2022-01-04   106   116  101    111    2500
2022-01-05   108   118  103    113    3000

重采样与窗口函数

重采样和窗口函数是处理时序数据的重要工具,可以用于降采样和升采样,以及计算滑动统计量。

重采样

# 按月重采样,计算每月的平均值
df_monthly = df.resample('M').mean()
print(df_monthly)

输出:

             Open   High    Low  Close  Volume
Date                                          
2022-01-31  104.0  114.0   99.0  109.0  2000.0

窗口函数

# 计算7天的滑动平均
df['7D_MA'] = df['Close'].rolling(window=7).mean()
print(df)

输出:

            Open  High  Low  Close  Volume  7D_MA
Date                                            
2022-01-01   100   110   95    105    1000    NaN
2022-01-02   102   112   97    107    1500    NaN
2022-01-03   104   114   99    109    2000    NaN
2022-01-04   106   116  101    111    2500    NaN
2022-01-05   108   118  103    113    3000    NaN

由于示例数据仅有5天,因此7天滑动平均值为NaN。

缺失值处理

在时序数据中,缺失值是常见的问题。pandas提供了多种方法来处理缺失值。

填充缺失值

# 向前填充缺失值
df['7D_MA'] = df['7D_MA'].fillna(method='ffill')
print(df)

删除缺失值

# 删除包含缺失值的行
df_cleaned = df.dropna()
print(df_cleaned)

时序数据的可视化

可视化是时序数据分析的重要部分,pandas与matplotlib集成,可以方便地进行时序数据的可视化。

import matplotlib.pyplot as plt

# 绘制收盘价和7天滑动平均
df[['Close', '7D_MA']].plot(figsize=(10, 5))
plt.title('收盘价和7天滑动平均')
plt.xlabel('日期')
plt.ylabel('价格')
plt.show()

高级时序分析

自相关与偏自相关

自相关和偏自相关是时序分析中用于检查数据序列中的依赖关系。

from statsmodels.graphics.tsaplots import plot_acf, plot_pacf

# 绘制自相关图
plot_acf(df['Close'], lags=20)
plt.show()

# 绘制偏自相关图
plot_pacf(df['Close'], lags=20)
plt.show()

ARIMA模型

ARIMA(AutoRegressive Integrated Moving Average)模型是时序分析中的经典模型,用于预测和分析时序数据。

from statsmodels.tsa.arima_model import ARIMA

# 拟合ARIMA模型
model = ARIMA(df['Close'], order=(5, 1, 0))
model_fit = model.fit(disp=0)

# 打印模型总结
print(model_fit.summary())

# 绘制预测结果
model_fit.plot_predict(dynamic=False)
plt.show()

总结

本文详细介绍了Python pandas在时序统计中的高级用法,包括数据加载与预处理、时间索引与切片、重采样与窗口函数、缺失值处理以及时序数据的可视化和高级分析技术。通过具体的示例代码,展示了如何有效地处理和分析时序数据,深入挖掘数据中的趋势和模式。掌握这些技巧和方法,可以在实际工作中更高效地进行时序数据分析,提高数据处理的能力和效率。


Python学习路线

在这里插入图片描述

更多资料获取

📚 个人网站:ipengtao.com

如果还想要领取更多更丰富的资料,可以点击文章下方名片,回复【优质资料】,即可获取 全方位学习资料包。

在这里插入图片描述
点击文章下方链接卡片,回复【优质资料】,可直接领取资料大礼包。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值