PySpark技术需求:将B组前的A组描述聚合为数组关联至B组
聚合A组记录关联到对应B组的实现方案
需求说明
现有包含A、B两组的数据集,A组的Description列存储关联详情。要求每当出现B组记录时,把该记录之前所有未被关联过的A组Description内容聚合为数组,绑定到这条B组记录上,最终生成只包含B组记录的新数据集。
样本数据集
| Description | Group |
|---|---|
| XYZ | A |
| PQR | A |
| B | |
| DEF | A |
| HIJ | A |
| KLM | A |
| NOP | A |
| B |
预期输出
| Group | Description |
|---|---|
| B | [XYZ,PQR] |
| B | [DEF,HIJ,KLM,NOP] |
实现方案
Python Pandas 实现
通过标记B组的分组区间,对对应A组数据进行聚合:
import pandas as pd # 构造样本数据 df = pd.DataFrame({ 'Description': ['XYZ', 'PQR', '', 'DEF', 'HIJ', 'KLM', 'NOP', ''], 'Group': ['A', 'A', 'B', 'A', 'A', 'A', 'A', 'B'] }) # 生成分组ID:每遇到B组,ID加1,A组沿用前一个ID df['b_group_id'] = df['Group'].eq('B').cumsum() # 聚合每个分组下的A组Description aggregated = df[df['Group'] == 'A'].groupby('b_group_id')['Description'].agg(list).reset_index() # 整理成预期格式 aggregated['Group'] = 'B' final_result = aggregated[['Group', 'Description']] print(final_result)
SQL 实现(以MySQL为例)
利用窗口函数标记B组区间,再聚合A组数据:
WITH marked_data AS ( SELECT Description, `Group`, SUM(CASE WHEN `Group` = 'B' THEN 1 ELSE 0 END) OVER (ORDER BY your_sort_column) AS b_group_id FROM your_table ), a_aggregated AS ( SELECT b_group_id, CONCAT('[', GROUP_CONCAT(Description SEPARATOR ','), ']') AS Description FROM marked_data WHERE `Group` = 'A' GROUP BY b_group_id ) SELECT 'B' AS `Group`, Description FROM a_aggregated;
注:your_sort_column需替换为实际的排序字段(比如主键、时间戳),保证数据按原始顺序处理。
内容的提问来源于stack exchange,提问作者BiggieIt
相关产品推荐
相关产品推荐

