You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PySpark处理犯罪数据集:绘制2019-2021年月度时间序列折线图

犯罪数据月度统计与折线图绘制方案

步骤1:校准日期列格式

先把数据中的日期列转为datetime类型,否则无法进行时间维度的聚合操作:

import pandas as pd

# 替换成你数据集里的日期列名称
df['date'] = pd.to_datetime(df['date'])

步骤2:筛选目标年份数据

用布尔索引直接定位2019-2021年的记录,比filter+agg组合更直观:

# 筛选2019、2020、2021三年的数据
target_df = df[(df['date'].dt.year >= 2019) & (df['date'].dt.year <= 2021)]

步骤3:按月统计案件总数

提供两种新手友好的聚合方法:

方法一:resample(推荐,专为时间序列设计)

resample('M')会自动按月分组,size()统计每组的案件数量:

# 按月聚合,生成每月案件总数表格
monthly_crimes = target_df.resample('M', on='date').size().reset_index(name='total_cases')
# 参数说明:'M'代表月度聚合,on指定时间列,name设置统计结果的列名

方法二:groupby

先构造“年月”列,再分组统计:

# 添加年月列,格式如"2019-01"
target_df['year_month'] = target_df['date'].dt.to_period('M')
# 按年月分组统计案件数
monthly_crimes = target_df.groupby('year_month').size().reset_index(name='total_cases')
# 若后续绘图需要连续时间轴,可转成datetime类型
monthly_crimes['year_month'] = monthly_crimes['year_month'].dt.to_timestamp()

步骤4:绘制月度折线图

用matplotlib快速生成可视化图表:

import matplotlib.pyplot as plt

plt.figure(figsize=(12, 6))
# 注意替换列名:用resample生成的表用'date',用groupby生成的表用'year_month'
plt.plot(monthly_crimes['date'], monthly_crimes['total_cases'], marker='o', linestyle='-', color='#2c3e50')
plt.title('2019-2021年每月犯罪案件总数')
plt.xlabel('月份')
plt.ylabel('案件总数')
# 旋转x轴标签避免重叠
plt.xticks(rotation=45)
# 自动调整布局防止标签被截断
plt.tight_layout()
plt.show()

新手常见问题提示

  • 若日期列存在无效值,转换datetime时可加errors='coerce'将无效值转为NaT,再用dropna()删除:df['date'] = pd.to_datetime(df['date'], errors='coerce'),df = df.dropna(subset=['date'])
  • 如果你的数据是按类别统计的(而非每行对应一个案件),可把size()替换为sum(),比如agg({'case_count_column': 'sum'})

内容的提问来源于stack exchange,提问作者slycooper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 03:15:51