Python 基础入门 Day23

54次阅读
没有评论

共计 1965 个字符,预计需要花费 5 分钟才能阅读完成。

欢迎来到 Python 基础入门 Day23!今天,我们将继续探索 Pandas 的强大功能,结合昨天学习的时间序列操作,深入研究 时间序列分析与数据透视表结合的应用 ,并介绍一些常用的可视化方法。


目录

  1. 时间序列结合数据透视表的应用
  2. 时间序列数据的可视化
  3. 使用窗口函数分析趋势和季节性
  4. 小结与练习

一、时间序列结合数据透视表的应用

1.1 按月份分组计算数据

在处理时间序列数据时,按月份、季度等时间维度汇总数据是一种常见操作。利用 Pandas 的 groupby()pivot_table() 可以轻松实现。

import pandas as pd
import numpy as np

# 示例数据
date_rng = pd.date_range(start="2024-01-01", end="2024-12-31", freq="D")
data = {
    "Date": date_rng,
    "Sales": np.random.randint(100, 500, size=(len(date_rng))),
    "Category": np.random.choice(["A", "B", "C"], size=len(date_rng)),
}
df = pd.DataFrame(data)

# 设置日期为索引
df.set_index("Date", inplace=True)

# 按月份计算销售总额
monthly_sales = df.resample("M")["Sales"].sum()
print(monthly_sales)

1.2 使用数据透视表结合时间序列

通过数据透视表,可以按时间和类别等多维度同时聚合数据。

# 按月份和类别计算销售总额
pivot = pd.pivot_table(
    df,
    values="Sales",
    index=df.index.to_period("M"),  # 按月份聚合
    columns="Category",
    aggfunc="sum",
    fill_value=0,
)
print(pivot)

二、时间序列数据的可视化

2.1 折线图

折线图是时间序列数据的主要可视化方式,能直观展现数据随时间的变化。

import matplotlib.pyplot as plt

# 绘制月度销售额折线图
monthly_sales.plot(title="Monthly Sales")
plt.xlabel("Month")
plt.ylabel("Total Sales")
plt.show()

2.2 多维度时间序列可视化

可以为不同类别绘制多条曲线。

# 绘制各类别的月度销售额折线图
pivot.plot(title="Monthly Sales by Category")
plt.xlabel("Month")
plt.ylabel("Total Sales")
plt.legend(title="Category")
plt.show()

三、使用窗口函数分析趋势和季节性

3.1 滑动平均

滑动平均是分析长期趋势的重要工具。

# 计算 7 天滑动平均
df["7D_MA"] = df["Sales"].rolling(window=7).mean()

# 可视化
df["Sales"].plot(label="Daily Sales", alpha=0.5)
df["7D_MA"].plot(label="7-Day Moving Average", linewidth=2)
plt.title("Daily Sales and 7-Day Moving Average")
plt.legend()
plt.show()

3.2 季节性分解

使用 statsmodels 的季节性分解可以分离数据的趋势、季节性和残差。

from statsmodels.tsa.seasonal import seasonal_decompose

# 季节性分解
result = seasonal_decompose(df["Sales"], model="additive", period=365)
result.plot()
plt.show()

四、小结与练习

今天,我们学习了:

  1. 如何结合时间序列和数据透视表进行多维度数据分析。
  2. 使用 Pandas 和 Matplotlib 对时间序列数据进行可视化。
  3. 使用窗口函数和季节性分解分析数据的长期趋势和季节性特征。

今日练习题:

  1. 创建一个时间序列数据,包含以下列:
    • 日期(从 2023-01-01 到 2024-12-31)。
    • 每日随机销售额。
    • 产品类别(随机分为 3 类:A、B 和 C)。
  2. 按季度计算每类产品的销售总额,并生成数据透视表。
  3. 绘制按季度的折线图,分别展示不同类别的销售趋势。
  4. 计算 30 天的滑动平均值,并绘制滑动平均值与每日销售额的对比图。

下一节预告 :在 Day24 中,我们将开始学习 Matplotlib 的高级可视化技巧 ,为我们的数据分析增添更多生动的图表形式。敬请期待!


今天的学习就到这里!如果有任何问题,欢迎随时讨论 😊。

正文完
 0
评论(没有评论)