SQL与Python实现用户ID首Before末After值变化次数统计
SQL 实现
核心逻辑分3步:
- 提取每个ID的首条Before值、末条After值
- 统计每个「X to Y」组合的出现次数
- 生成全部9种可能的组合,补全计数为0的条目
完整可运行SQL代码:
WITH id_first_last AS ( -- 取每个ID的首Before和末After,去重得到每个ID仅一行数据 SELECT DISTINCT ID, FIRST_VALUE(Before) OVER (PARTITION BY ID ORDER BY Date ASC) AS first_before, LAST_VALUE(After) OVER (PARTITION BY ID ORDER BY Date ASC ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS last_after FROM data ), -- 生成所有可能的变化组合 all_changes AS ( SELECT concat(a.val, ' to ', b.val) AS changes FROM (SELECT 4 AS val UNION ALL SELECT 5 UNION ALL SELECT 6) a CROSS JOIN (SELECT 4 AS val UNION ALL SELECT 5 UNION ALL SELECT 6) b ), -- 统计实际出现的组合次数 change_count AS ( SELECT concat(first_before, ' to ', last_after) AS changes, count(*) AS tot_count FROM id_first_last GROUP BY concat(first_before, ' to ', last_after) ) -- 左关联补全0值 SELECT ac.changes, COALESCE(cc.tot_count, 0) AS `Tot.Count` FROM all_changes ac LEFT JOIN change_count cc ON ac.changes = cc.changes ORDER BY ac.changes;
Python 实现(基于Pandas)
代码如下:
import pandas as pd import itertools def count_change(data_df: pd.DataFrame) -> pd.DataFrame: # 1. 按日期排序后分组,取每个ID最早的Before、最晚的After id_stat = data_df.sort_values('Date').groupby('ID').agg( first_before=('Before', 'first'), last_after=('After', 'last') ).reset_index() # 2. 统计现有组合的出现频次 id_stat['changes'] = id_stat['first_before'].astype(str) + ' to ' + id_stat['last_after'].astype(str) cnt = id_stat['changes'].value_counts() # 3. 生成全部9种组合,补全0计数条目 all_vals = [4,5,6] all_changes = [f"{a} to {b}" for a,b in itertools.product(all_vals, all_vals)] result = pd.DataFrame({ 'Changes': all_changes, 'Tot.Count': [cnt.get(c, 0) for c in all_changes] }) return result # 调用示例 # 读取数据表:df = pd.read_csv('数据文件路径', parse_dates=['Date']) # res = count_change(df) # print(res)
内容的提问来源于stack exchange,提问作者Blackdynomite
相关产品推荐
相关产品推荐

