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

Data Science入门:基于日期范围创建季度分桶Histogram求助

按季度分桶的活动数量分布可视化方案

实现步骤(基于Python Pandas + Matplotlib)

1. 数据预处理

先确保日期列被正确转换为datetime类型,再根据自定义季度规则生成对应标签。

2. 基础实现(手写条件判断)

针对你提到的特殊季度规则(如2020年Q1仅包含3.15-3.31),可以通过自定义函数生成季度标识:

import pandas as pd
import matplotlib.pyplot as plt

# 替换为你的数据读取逻辑
# df = pd.read_csv("your_dataset.csv")

# 转换日期列为datetime类型
df["date"] = pd.to_datetime(df["date"])

# 自定义季度映射函数
def map_to_quarter(date):
    year = date.year
    month = date.month
    if year == 2020 and month == 3 and date.day >= 15:
        return "Q1-2020"
    elif year == 2020 and month in [4,5,6]:
        return "Q2-2020"
    elif year == 2020 and month in [7,8,9]:
        return "Q3-2020"
    elif year == 2020 and month in [10,11,12]:
        return "Q4-2020"
    elif year == 2021 and month in [1,2,3]:
        return "Q1-2021"
    elif year == 2021 and month in [4,5,6]:
        return "Q2-2021"
    elif year == 2021 and month in [7,8,9]:
        return "Q3-2021"
    elif year == 2021 and month in [10,11,12]:
        return "Q4-2021"
    elif year == 2022 and month in [1,2] and date <= pd.to_datetime("2022-02-23"):
        return "Q1-2022"
    return "Other"

# 添加季度列
df["quarter"] = df["date"].apply(map_to_quarter)

# 统计每个季度的活动数量并按季度排序
quarter_activity_count = df["quarter"].value_counts().sort_index()

# 绘制柱状图(对应你要求的直方图效果)
plt.figure(figsize=(10,6))
quarter_activity_count.plot(kind="bar", color="#87CEEB")
plt.title("季度活动数量分布")
plt.xlabel("季度")
plt.ylabel("活动数量")
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

3. 更优解决方案(使用Pandas Cut分桶)

用pd.cut()替代手写条件,代码更简洁、可扩展性更强,后续调整日期范围只需修改分桶边界即可:

import pandas as pd
import matplotlib.pyplot as plt

# 替换为你的数据读取逻辑
# df = pd.read_csv("your_dataset.csv")
df["date"] = pd.to_datetime(df["date"])

# 定义自定义季度的时间边界(左闭右开,include_lowest=True确保包含起始日期)
time_bins = [
    pd.to_datetime("2020-03-14"),
    pd.to_datetime("2020-04-01"),
    pd.to_datetime("2020-07-01"),
    pd.to_datetime("2020-10-01"),
    pd.to_datetime("2021-01-01"),
    pd.to_datetime("2021-04-01"),
    pd.to_datetime("2021-07-01"),
    pd.to_datetime("2021-10-01"),
    pd.to_datetime("2022-01-01"),
    pd.to_datetime("2022-02-24")
]

# 对应每个桶的季度标签
quarter_labels = [
    "Q1-2020", "Q2-2020", "Q3-2020", "Q4-2020",
    "Q1-2021", "Q2-2021", "Q3-2021", "Q4-2021",
    "Q1-2022"
]

# 生成季度列
df["quarter"] = pd.cut(df["date"], bins=time_bins, labels=quarter_labels, include_lowest=True)

# 统计排序并绘图
quarter_activity_count = df["quarter"].value_counts().sort_index()

plt.figure(figsize=(10,6))
quarter_activity_count.plot(kind="bar", color="#87CEEB")
plt.title("季度活动数量分布")
plt.xlabel("季度")
plt.ylabel("活动数量")
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

注意事项

  • 由于你的分桶是离散的季度类别,使用柱状图(bar plot)比传统直方图(针对连续数据)更贴合需求,和你提供的示例图效果一致。
  • 如果数据集是按日期聚合好的(每行是单日活动总数),只需将value_counts()替换为df.groupby("quarter")["activity_count"].sum()即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 15:00:57