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

Pandas DataFrame按月统计人员Attempt为Yes的次数并填充Count列

实现方案

你可以用pandas的分组聚合+表合并的方式实现需求,具体步骤和代码如下:

  1. 先把Date列转换为日期格式,提取年月作为分组的时间维度
  2. 筛选出Attempt取值为Yes的记录,按「姓名+年月」分组统计次数
  3. 将统计结果合并回原DataFrame,无匹配记录(即当月该用户没有Yes记录)的Count字段填充为0
  4. 删除辅助字段即可得到目标结果

完整可运行代码:

import pandas as pd

# 构造示例数据,替换为你自己的DataFrame即可
df = pd.DataFrame({
    'Date': ['2015-01-02', '2015-01-29', '2015-02-02', '2015-03-02', '2015-03-02', '2015-03-02'],
    'Name': ['Adam', 'Adam', 'David', 'David', 'Hardik', 'David'],
    'Attempt': ['Yes', 'Yes', 'No', 'Yes', 'Yes', 'No']
})

# 生成年月辅助列
df['year_month'] = pd.to_datetime(df['Date']).dt.to_period('M')

# 统计每月每人Yes次数
count_result = df[df['Attempt'] == 'Yes'].groupby(['Name', 'year_month'], as_index=False)['Attempt'].count().rename(columns={'Attempt': 'Count'})

# 合并回原表,缺失值填0
df = df.merge(count_result, on=['Name', 'year_month'], how='left').fillna({'Count': 0})

# 转换Count为整数,删除辅助列
df['Count'] = df['Count'].astype(int)
df = df.drop(columns='year_month')

print(df)

运行后输出的结果和你给出的预期完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 21:21:00