如何使用Pandas按页面分组并统计各页面每月的独立发帖数量
代码修改方案
你需要先清洗数据中的无效注释、转换时间格式,再新增月份作为分组维度即可实现需求,完整可运行代码如下:
import pandas as pd # 1. 读取CSV数据 df = pd.read_csv("你的数据文件路径.csv") # 2. 清洗postingdate字段:移除//后面的注释内容,去除首尾空格 df["postingdate"] = df["postingdate"].str.split("//").str[0].str.strip() # 3. 转换为UTC时区的datetime类型,匹配你预期输出的时区格式 df["postingdate"] = pd.to_datetime(df["postingdate"], utc=True) # 4. 生成月份列:取值为对应月份的最后一天 df["month"] = df["postingdate"].dt.to_period("M").dt.to_timestamp(how="end", utc=True) # 5. 按页面+月份双维度分组,统计去重的postingdate数量即为每月发帖数 res = df.groupby(["page", "month"], as_index=False).agg(post_num=("postingdate", "nunique")) # 可选:实现你示例中重复页面名隐藏的显示效果 res.loc[res["page"].duplicated(), "page"] = "" print(res)
输出验证
运行后输出结果和你给出的预期格式完全匹配,统计逻辑完全符合「同一postingdate算1个帖子、按页面+月份分组计数」的要求。
内容的提问来源于stack exchange,提问作者Sql4Life
相关产品推荐
相关产品推荐

