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

如何用Python(Jupyter Notebook)基于多查询CSV绘制每月事件数统计图

当然可以呀!作为Python新手,在Jupyter Notebook里实现这个需求完全没难度,我给你一步步捋清楚怎么做~

第一步:准备好需要的工具库

首先我们需要两个常用的Python库:pandas用来处理数据,matplotlib用来画图。在Jupyter Notebook的单元格里输入以下代码并运行:

import pandas as pd
import matplotlib.pyplot as plt

如果运行时提示“找不到模块”,就在Jupyter的单元格里先安装依赖:

!pip install pandas matplotlib
第二步:读取并整理你的CSV数据

你的CSV文件包含了12个月份的独立查询结果,我假设每个月份的数据块开头会有“一月”“二月”这类明确的月份标识(如果你的CSV结构不一样,可以随时调整逻辑)。我们逐行读取文件,统计每个月的事件条数:

# 替换成你自己的CSV文件路径,比如'./monthly_events.csv'
file_path = '你的CSV文件名.csv'

month_counts = {}
current_month = None

# 逐行读取文件
with open(file_path, 'r', encoding='utf-8') as f:
    for line in f:
        # 去掉每行首尾的空格和换行符
        clean_line = line.strip()
        # 判断当前行是不是月份名称
        month_names = ['一月', '二月', '三月', '四月', '五月', '六月', 
                       '七月', '八月', '九月', '十月', '十一月', '十二月']
        if clean_line in month_names:
            current_month = clean_line
            # 初始化该月份的计数为0
            month_counts[current_month] = 0
        # 如果是数据行(非空且当前已经匹配到月份),计数加1
        elif clean_line and current_month is not None:
            month_counts[current_month] += 1

# 把统计结果转成DataFrame,方便后续画图
df_counts = pd.DataFrame(list(month_counts.items()), columns=['月份', '事件数量'])

# 按月份顺序排序,避免图里的月份乱序
month_order = ['一月', '二月', '三月', '四月', '五月', '六月', 
               '七月', '八月', '九月', '十月', '十一月', '十二月']
df_counts['月份'] = pd.Categorical(df_counts['月份'], categories=month_order, ordered=True)
df_counts = df_counts.sort_values('月份')
第三步:绘制统计图

现在我们用柱状图来展示每个月的事件数量,代码里已经处理了中文显示的问题,避免乱码:

# 设置中文字体,解决matplotlib中文乱码问题
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

# 创建图形,设置大小
plt.figure(figsize=(12, 6))
# 画柱状图
plt.bar(df_counts['月份'], df_counts['事件数量'], color='skyblue')

# 添加标题和坐标轴标签
plt.title('各月份事件数量统计', fontsize=16)
plt.xlabel('月份', fontsize=12)
plt.ylabel('事件数量', fontsize=12)

# 在每个柱子上方显示具体数值
for index, value in enumerate(df_counts['事件数量']):
    plt.text(index, value + 1, str(value), ha='center', fontsize=10)

# 显示图形
plt.show()
小提示

如果你的CSV结构和我假设的不一样(比如每个月份的数据块都带重复表头),可以告诉我具体的格式细节,我再帮你调整代码~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:05:16