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

如何利用Pandas找出每月新增及已删除的address_id?

解决Pandas中每月新增/删除address_id的统计问题

步骤1:预处理日期数据

先把日期列转成datetime格式,提取YYYY-MM格式的月份字段,方便后续按月份分组:

import pandas as pd

# 假设你的数据集存储在df中
df['mydate'] = pd.to_datetime(df['mydate'])
df['month'] = df['mydate'].dt.to_period('M')

步骤2:统计每月新增的address_id

新增ID的核心是找出每个address_id首次出现的月份,再按月份聚合:

# 先获取每个ID的首次出现月份
first_occur = df.groupby('address_id')['month'].min().reset_index()
first_occur.columns = ['address_id', 'first_month']

# 按月份分组,得到当月新增的ID列表
new_ids_per_month = first_occur.groupby('first_month')['address_id'].apply(list).reset_index()
new_ids_per_month.columns = ['month', 'new_address_ids']

步骤3:统计每月活跃的address_id集合

先拿到每个月份存在的所有唯一address_id,用集合存储方便后续对比:

active_ids_per_month = df.groupby('month')['address_id'].apply(set).reset_index()
active_ids_per_month.columns = ['month', 'active_ids']

步骤4:计算每月删除的address_id

删除的ID指上月活跃但当月未出现的ID,通过对比相邻月份的活跃集合得到:

# 先按月份排序,保证顺序正确
active_ids_per_month = active_ids_per_month.sort_values('month')

# 关联上月的活跃ID集合
active_ids_per_month['prev_active'] = active_ids_per_month['active_ids'].shift(1)

# 计算删除的ID列表
active_ids_per_month['deleted_address_ids'] = active_ids_per_month.apply(
    lambda row: list(row['prev_active'] - row['active_ids']) if pd.notna(row['prev_active']) else [],
    axis=1
)

合并最终结果

把新增和删除的统计结果合并成一个DataFrame,方便查看:

final_result = pd.merge(
    new_ids_per_month,
    active_ids_per_month[['month', 'deleted_address_ids']],
    on='month',
    how='outer'
)
# 空值填充为空列表
final_result['new_address_ids'] = final_result['new_address_ids'].fillna({i: [] for i in final_result.index})

示例效果

假设原始数据如下:

address_id  mydate
111         2022-03-10
222         2022-03-15
333         2022-03-20
111         2022-04-05
333         2022-04-10
555         2022-04-16

运行代码后,final_result的输出为:

monthnew_address_idsdeleted_address_ids
2022-03[111, 222, 333][]
2022-04[555][222]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 07:39:22