Introduction to Time Series Analysis with a Python Example
This article explains the concept of time series, describes its main patterns such as long‑term trend, seasonal, cyclical and random variations, and demonstrates a practical Python analysis of a three‑year sales dataset from a Taobao shop using pandas and matplotlib.
Overview: A time series is a sequence of data points ordered by time, and time series analysis seeks to discover patterns in the data to forecast future trends.
Time series analysis can be expressed in several forms:
Long‑term trend: steady increase or decrease over time, analyzed with methods like moving average or exponential smoothing.
Seasonal cycle: regular periodic changes caused by seasons or other cycles (e.g., monthly, weekly), analyzed using seasonal indices.
Cyclical variation: longer cycles lasting 2–15 years.
Random variation: unpredictable changes caused by many uncertain factors.
Case Study – Annual Growth Trend and Seasonal Fluctuation: An analysis of a Taobao shop’s revenue over the past three years shows a steady upward trend with a noticeable dip in 2019 and clear seasonal peaks in the fourth quarter each year.
Program code:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_excel('TB.xls')
df1 = df[['订单付款时间','买家实际支付金额']]
df1 = df1.set_index('订单付款时间') # 将“订单付款时间”设置为索引
plt.rcParams['font.sans-serif'] = ['SimHei'] # 解决中文乱码
# 按年统计数据
df_y = df1.resample('AS').sum().to_period('A')
print(df_y)
# 按季度统计数据
df_q = df1.resample('Q').sum().to_period('Q')
print(df_q)
# 绘制子图
fig = plt.figure(figsize=(8,3))
ax = fig.subplots(1,2)
df_y.plot(subplots=True, ax=ax[0])
df_q.plot(subplots=True, ax=ax[1])
# 调整图表距上部和底部的空白
plt.subplots_adjust(top=0.95, bottom=0.2)
plt.show()The article also includes promotional material for a free Python public course and additional reading links, but the core educational content focuses on explaining time‑series concepts and demonstrating a practical Python implementation.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.