数据可视化(八):Pandas时间序列——动态绘图,重采样,自相关图,偏相关图等高级操作

Tips:"分享是快乐的源泉💧,在我的博客里,不仅有知识的海洋🌊,还有满满的正能量加持💪,快来和我一起分享这份快乐吧😊!

喜欢我的博客的话,记得点个红心❤️和小关小注哦!您的支持是我创作的动力!数据源存放在我的资源下载区啦!

数据可视化(八):Pandas时间序列——动态绘图,重采样,自相关图,偏相关图等高级操作

1. 时间序列分析1

股票(上证600519)分析

文件:assets/SH600519.csv

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt # 绘图使用
# 支持中文
plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']  # SimHei 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
%matplotlib inline 

# 读取数据

df = pd.read_csv('SH600519.csv', index_col=0)  # 读取 上证600519 贵州茅台股票数据 index_col=0表示去掉自动增添的索引列
df.sample(5)

问题1:将列 date 转化为日期时间类型,并设置为索引

# 代码
# 转化 'date' 列为 datetime 类型  
df['date'] = pd.to_datetime(df['date'])  
  
# 设置 'date' 列为索引  
df.set_index('date', inplace=True)
df.head()

问题2:按年份 统计开盘价(open列) 均值,并绘制直方图

# 代码
# 提取年份  
df['year'] = df.index.year  
  
# 按年份分组并计算开盘价的均值  
mean_open_by_year = df.groupby('year')['open'].mean()  
  
# 但更常见的是使用条形图来展示每年的均值  
mean_open_by_year.plot(kind='bar')  
plt.xlabel('Year')  
plt.xticks(rotation=45)  # 如果年份标签太长,可以旋转显示  
plt.ylabel('Mean Opening Price')  
plt.title('Mean Opening Price by Year (Bar Chart)')  
plt.show()

问题3:重采样,按月分析 open 列均值,并绘制折线图

# 代码
# 重采样,按月计算 open 列的均值  
monthly_mean_open = df['open'].resample('M').mean()  
  
# 绘制折线图  
plt.figure(figsize=(10, 5))  # 设置图形大小  
plt.plot(monthly_mean_open.index, monthly_mean_open.values, marker='o')  
plt.xlabel('Date')  
plt.ylabel('Mean Opening Price')  
plt.title('Monthly Mean Opening Price')  
plt.xticks(rotation=45)  # 如果日期标签重叠,可以旋转显示  
plt.grid(True)  # 显示网格线  
plt.show()

2. 时间序列分析2

销售企业数据时间序列分析。

数据集合的列名含义:

数据:assets/Month_Value_1.csv

Period Revenue Sales_quantity Average_cost The_average_annual_payroll_of_the_region

时期 收入 销售量 平均成本 该地区每年的员工平均薪酬总额

#读取数据

df = pd.read_csv('Month_Value_1.csv')  # 读取数据
display( df.head(5) )
df.info()

问题1:将列 Period 转化为 日期时间(datetime) 类型,并按列 Period 排序。

# 编码
# 转化 'Period' 列为 datetime 类型  
df['Period'] = pd.to_datetime(df['Period'])
df = df.sort_values(by="Period",ascending=True).reset_index(drop=True)
df.head()

问题2:将列 Period 转化为 时期(Period)类型,并设置为索引

# 编码
# 将 'Period' 列转化为 Period 类型  
# 然后将 datetime 转换为 Period 类型(假设频率为日)  
df['Period'] = df['Period'].dt.to_period('d')   
  
# 将 'Period' 列设置为索引  
df.set_index('Period', inplace=True)  
  
# 查看结果  
df.head()

问题3:删除还有缺失值的行,绘制Sales_quantity列的自相关图和偏自相关图

  • 自相关图是一种展示时间序列数据与其自身过去值之间相关性的图形。在统计和数据分析中,自相关图常被用于识别序列中的周期性或趋势,以及评估数据的随机性。通过自相关图,可以观察到数据在不同时间间隔上的相关性程度,从而帮助理解和分析数据的特性。
  • 偏自相关图是一种用于展示时间序列数据中某一时刻的值与其之前时刻的值之间的直接(非间接)相关性的图形。与自相关图不同,偏自相关图在计算相关性时,会排除其他时间点上的值所带来的间接影响,从而更直接地反映两个时间点之间的相关性。
# 编码
# 删除缺失值的行
df = df.dropna()
df.info()

df.dtypes

from statsmodels.graphics.tsaplots import plot_acf, plot_pacf 
import warnings  
warnings.filterwarnings("ignore")

# 绘制 Sales_quantity 列的自相关图  
fig, ax = plt.subplots(figsize=(10, 5))  
plot_acf(df['Sales_quantity'], lags=40, ax=ax)  
plt.title('Autocorrelation Function of Sales_quantity')  
plt.show()  
  
# 绘制 Sales_quantity 列的偏自相关图  
fig, ax = plt.subplots(figsize=(10, 5))  
plot_pacf(df['Sales_quantity'], lags=40, ax=ax)  
plt.title('Partial Autocorrelation Function of Sales_quantity')  
plt.show()

问题4:绘制收入(Revenue)和销售量(Sales_quantity)随Period变化的折线图

#编码
df.dtypes

df.index

# 将索引转换为日期时间类型
df.index = df.index.to_timestamp()

# 确认索引已经转换为日期时间类型
df.index

# 然后再绘制折线图
plt.figure(figsize=(10, 6))
plt.plot(df.index, df['Revenue'], label='Revenue')
plt.plot(df.index, df['Sales_quantity'], label='Sales_quantity')
plt.xlabel('Period')
plt.ylabel('Amount')
plt.title('Revenue and Sales Quantity Over Time')
plt.legend()
plt.show()

问题5:通过3期滚动平均值和标准差,绘制收入和销售量数据折线图,判断其是否平稳

#编码
# 计算3期滚动平均值和标准差
rolling_mean = df.rolling(window=3).mean()
rolling_std = df.rolling(window=3).std()

# 绘制原始数据的折线图
plt.figure(figsize=(10, 6))
plt.plot(df.index, df['Revenue'], label='Revenue')
plt.plot(df.index, df['Sales_quantity'], label='Sales_quantity')

# 绘制滚动平均值和标准差的折线图
plt.plot(rolling_mean.index, rolling_mean['Revenue'], label='Rolling Mean (3 periods)', linestyle='--')
plt.plot(rolling_std.index, rolling_std['Revenue'], label='Rolling Std (3 periods)', linestyle='--')

plt.plot(rolling_mean.index, rolling_mean['Sales_quantity'], label='Rolling Mean (3 periods)', linestyle='--')
plt.plot(rolling_std.index, rolling_std['Sales_quantity'], label='Rolling Std (3 periods)', linestyle='--')

plt.xlabel('Period')
plt.ylabel('Amount')
plt.title('Revenue and Sales Quantity Over Time with Rolling Mean and Standard Deviation')
plt.legend()
plt.show()

时间序列分析3

销售数据分析。

数据:assets/sale_train.csv

数据列:

Date store product number_sold

日期 商店ID 产品ID 销售数量

# 读取数据

df = pd.read_csv('sale_train.csv')  # 读取数据
display( df.sample(5) )
df.info()

问题1:按日期统计销售量,绘制销售数量的折线图,观察是否具备周期性

# 编码
# 将日期列转换为日期时间类型,并将其设置为索引
df['Date'] = pd.to_datetime(df['Date'])
df.set_index('Date', inplace=True)
df.head()

df.dtypes

df.index

问题2:将Date列转换为datetime类型,并作为索引。

# 编码
# 按日期统计销售量
sales_by_date = df.groupby(df.index).sum()

# 绘制销售数量的折线图
plt.figure(figsize=(10, 6))
plt.plot(sales_by_date.index, sales_by_date['number_sold'], marker='o')
plt.xlabel('Date')
plt.ylabel('Number of Sales')
plt.title('Sales Quantity Over Time')
plt.grid(True)
plt.show()

问题3:对上一题生成dataframe重新采样(按月和按年)后计算number_sold总量,然后绘制number_sold总量的折线图。

# 编码
# 按月重新采样并计算每月的总销售量
sales_monthly = df.resample('M').sum()

# 按年重新采样并计算每年的总销售量
sales_annually = df.resample('Y').sum()

# 绘制总销售量的折线图
plt.figure(figsize=(8, 6))

# 绘制按月重新采样后的折线图
plt.subplot(2, 1, 1)
plt.plot(sales_monthly.index, sales_monthly['number_sold'], marker='o', color='b')
plt.xlabel('Date')
plt.ylabel('Total Number of Sales')
plt.title('Total Sales Quantity (Monthly)')
plt.grid(True)

# 绘制按年重新采样后的折线图
plt.subplot(2, 1, 2)
plt.plot(sales_annually.index, sales_annually['number_sold'], marker='o', color='g')
plt.xlabel('Year')
plt.ylabel('Total Number of Sales')
plt.title('Total Sales Quantity (Annually)')
plt.grid(True)

plt.tight_layout()
plt.show()

matplotlib绘图题

1. 仿照讲义中例子,采用calendar和matplotlib绘制月历,要实时获取当前年月。

如下图:

import calendar
import matplotlib.pyplot as plt

%matplotlib inline

# 编码
import calendar
import matplotlib.pyplot as plt
import datetime
# 获取 2024 年 4 ⽉的⽇历
cal = calendar.monthcalendar(2024, 4)
# 绘制⽇历
plt.figure(figsize=(12, 12))
plt.imshow(cal, cmap="rainbow")
plt.xlabel('星期')
plt.ylabel('日期')
# 获取当前时间的年和月  
# 获取当前时间  
current_time = datetime.datetime.now()  
  
# 格式化当前时间为“XXXX年XX月”的形式  
current_year_month = "{}年{:02d}月".format(current_time.year, current_time.month)  
  
# 使用格式化后的时间设置图表标题  
plt.title("当前时间: {}".format(current_year_month))
# 标记周末和⼯作⽇
for i in range(len(cal)):
    for j in range(len(cal[0])):
        if j in [0, 6]:
             plt.text(j, i, cal[i][j], color="red", ha='center', va='center')
        else:
             plt.text(j, i, cal[i][j], color="black", ha='center', va='center')
plt.show()

2. 采用matplotlib绘制动画,动态显示按月销量。

每秒更新一次,每次更新时显示下一个月的销售额。在动画中,折线图会随着时间的推移逐渐绘制出来,并在每个点上显示销售月份和销售额。

如下图:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

%matplotlib notebook

# 生成日期范围
dates = pd.date_range('2020-01', '2024-04', freq='M')

# 生成销售数据
np.random.seed(2024)
sales_data = pd.DataFrame({
    '日期': dates,
    '销售额': np.random.randint(100, 201, size=len(dates))
})

# 绘制折线图
plt.figure(figsize=(15, 6))
plt.plot(sales_data["日期"], sales_data["销售量"])
plt.xlabel('日期')
plt.ylabel("销售量")
plt.show()

  • 47
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
在进行时间序列预测时,通常需要先对时间序列进行分析和建模。其中,相关函数偏相关函数和滞后是非常有用的工具。 首先,相关函数(Correlogram)是用来研究时间序列自相关性的。它显示了时间序列在不同滞后期的自相关系数。在Python中,可以使用statsmodels库的plot_acf函数绘制相关函数。例如: ```python import pandas as pd import statsmodels.api as sm import matplotlib.pyplot as plt # 读取时间序列数据 data = pd.read_csv('data.csv', index_col='date', parse_dates=True) # 绘制相关函数 fig, ax = plt.subplots(figsize=(10, 5)) sm.graphics.tsa.plot_acf(data['value'], lags=50, ax=ax) plt.show() ``` 接着,偏相关函数(Partial Correlogram)是用来研究时间序列的偏自相关性的。它显示了时间序列在不同滞后期的偏自相关系数。在Python中,可以使用statsmodels库的plot_pacf函数绘制偏相关函数。例如: ```python import pandas as pd import statsmodels.api as sm import matplotlib.pyplot as plt # 读取时间序列数据 data = pd.read_csv('data.csv', index_col='date', parse_dates=True) # 绘制偏相关函数 fig, ax = plt.subplots(figsize=(10, 5)) sm.graphics.tsa.plot_pacf(data['value'], lags=50, ax=ax) plt.show() ``` 最后,滞后(Lag Plot)是用来研究时间序列自相关性的。它显示了时间序列与其自身在一个或多个滞后期的散点。在Python中,可以使用pandas库的lag_plot函数绘制滞后。例如: ```python import pandas as pd import matplotlib.pyplot as plt # 读取时间序列数据 data = pd.read_csv('data.csv', index_col='date', parse_dates=True) # 绘制滞后 pd.plotting.lag_plot(data['value']) plt.show() ``` 以上就是用Python绘制时间序列分析中常用的相关函数偏相关函数和滞后的方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

卡林神不是猫

如果您觉得有帮助可以鼓励小卡哦

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值