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

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

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

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

目录

1. 时间序列分析1

股票(上证600519)分析

文件:<assets/SH600519.csv>

python 复制代码
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 转化为日期时间类型,并设置为索引

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

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

python 复制代码
# 代码
# 提取年份  
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 列均值,并绘制折线图

python 复制代码
# 代码
# 重采样,按月计算 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

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

python 复制代码
#读取数据

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

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

python 复制代码
# 编码
# 转化 '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)类型,并设置为索引

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

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

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

python 复制代码
#编码
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期滚动平均值和标准差,绘制收入和销售量数据折线图,判断其是否平稳

python 复制代码
#编码
# 计算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 销售数量

python 复制代码
# 读取数据

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

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

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

df.dtypes

df.index

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

python 复制代码
# 编码
# 按日期统计销售量
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总量的折线图。

python 复制代码
# 编码
# 按月重新采样并计算每月的总销售量
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绘制月历,要实时获取当前年月。

如下图:

python 复制代码
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绘制动画,动态显示按月销量。

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

如下图:

python 复制代码
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()
相关推荐
红色石榴12 分钟前
Qt中文乱码解决
开发语言·qt
Htht11114 分钟前
【Qt】实现模拟触摸屏 上下滑动表格 的两种方式
开发语言·qt
A 八方14 分钟前
Python MongoDB
开发语言·python·mongodb
sz66cm2 小时前
Python基础 -- 使用Python实现ssh终端并实现数据处理与统计功能
开发语言·python·ssh
liangbm33 小时前
MATLAB系列02:MATLAB基础
开发语言·数据结构·笔记·matlab·教程·工程基础·高级绘图
ac-er88884 小时前
如何在Flask中实现国际化和本地化
后端·python·flask
Adolf_19934 小时前
Flask-WTF的使用
后端·python·flask
空城皆是旧梦4 小时前
python爬虫初体验(一)
爬虫·python
藓类少女4 小时前
正则表达式
数据库·python·mysql·正则表达式
change95134 小时前
PHP纯离线搭建(php 8.1.7)
开发语言·php