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

pandas如何按date和type分组统计install小于date的唯一id数

实现步骤

首先先将install和date字段转为标准datetime格式,避免字符串比较出错,空的date行不会参与分组,可直接忽略。

方法1:自定义apply实现(中小数据集适用)

核心逻辑是先提取所有需要统计的(date, type)唯一分组,再逐组过滤符合install < 当前分组date条件的唯一id统计:

import pandas as pd
import numpy as np

# 构造示例数据
df = pd.DataFrame({
    'install': ['2021-11-01', '2021-11-01', '2021-11-01', '2021-11-01', '2021-11-02', '2021-11-03', '2021-11-04'],
    'type': ['main', 'main', 'main', 'main', 'down', 'main', 'main'],
    'id': ['a1', 'a2', 'a3', 'a3', 'b4', 'b7', 'a3'],
    'date': [np.nan, '2021-11-02', '2021-11-02', '2021-11-02', '2021-11-05', '2021-11-05', '2021-11-05']
})

# 转换日期格式
df['install'] = pd.to_datetime(df['install'])
df['date'] = pd.to_datetime(df['date'])

# 提取所有非空的分组键
group_keys = df.dropna(subset=['date'])[['date', 'type']].drop_duplicates()

# 逐组统计符合条件的唯一id数
def calc_count(row):
    filter_mask = (df['type'] == row['type']) & (df['install'] < row['date'])
    return df.loc[filter_mask, 'id'].nunique()

group_keys['count'] = group_keys.apply(calc_count, axis=1)
print(group_keys)

方法2:merge关联实现(大数据集适用,效率更高)

如果数据量较大,逐行apply性能较低,可通过同type关联后过滤再分组的方式实现:

# 提取非空分组和所有去重的用户安装信息
groups = df.dropna(subset=['date'])[['date', 'type']].drop_duplicates()
uid_install = df[['type', 'id', 'install']].drop_duplicates()

# 按type关联后过滤符合条件的记录,再分组统计
res = groups.merge(uid_install, on='type')\
            .query('install < date')\
            .groupby(['date', 'type'], as_index=False)['id'].nunique()\
            .rename(columns={'id':'count'})
print(res)

两种方法输出结果都和预期一致:

date  type  count
0 2021-11-02  main      3
1 2021-11-05  down      1
2 2021-11-05  main      4

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 14:36:04