如何使用Python Pandas按年月分组统计访客人数并绘图
访客人数时间维度统计绘图实现方案
前置依赖导入与数据预处理
首先导入需要用到的库并完成日期字段格式转换:
import pandas as pd import matplotlib.pyplot as plt # 读取数据集 df = pd.read_csv("你的数据集文件路径.csv") # 将Date字段转换为pandas datetime格式,方便后续时间维度筛选 df["Date"] = pd.to_datetime(df["Date"])
特定年份访客统计绘图
以统计2023年各月访客人数为例,代码如下:
# 定义目标年份 target_year = 2023 # 筛选目标年份数据 year_data = df[df["Date"].dt.year == target_year] # 按月份聚合总访客数,reindex补全1-12月,无数据月份填充为0 monthly_visits = year_data.groupby(year_data["Date"].dt.month)["Total Visits"].sum().reindex(range(1,13), fill_value=0) # 绘制柱状图 plt.figure(figsize=(10,5)) plt.bar([f"{i}月" for i in range(1,13)], monthly_visits.values) plt.title(f"{target_year}年各月访客人数统计") plt.xlabel("月份") plt.ylabel("总访客数") plt.tick_params(axis='x', rotation=45) plt.tight_layout() plt.show()
特定月份访客统计绘图
以统计2023年10月每日访客人数为例,代码如下:
# 定义目标年月 target_year = 2023 target_month = 10 # 筛选目标年月数据 month_data = df[(df["Date"].dt.year == target_year) & (df["Date"].dt.month == target_month)] # 按日期聚合总访客数 daily_visits = month_data.groupby(month_data["Date"].dt.day)["Total Visits"].sum() # 绘制折线图 plt.figure(figsize=(10,5)) plt.plot(daily_visits.index, daily_visits.values, marker="o", color="#2E86AB") plt.title(f"{target_year}年{target_month}月每日访客人数统计") plt.xlabel("日期") plt.ylabel("总访客数") plt.grid(alpha=0.3) plt.tight_layout() plt.show()
可选优化点
- 聚合计算时可将
sum替换为mean、max等函数,适配不同统计需求 - 可以通过matplotlib的参数自定义图表样式,包括颜色、字体、标记类型等
- 如果需要统计周度维度的数据,可以用
dt.isocalendar().week获取周数后做聚合
内容的提问来源于stack exchange,提问作者xoxo
相关产品推荐
相关产品推荐

