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

如何在PySpark DataFrame中透视列并拼接marks字段?

PySpark 按mid拼接marks字段的实现方案

实现思路

按mid字段分组,先通过collect_list收集每个分组内的所有marks值,再用concat_ws以竖线(|)为分隔符将收集到的列表拼接成单个字符串。如果需要保证marks按index的顺序拼接,需先对mid和index进行排序,避免拼接顺序混乱。

代码示例

from pyspark.sql import SparkSession
from pyspark.sql.functions import collect_list, concat_ws, asc

# 初始化SparkSession
spark = SparkSession.builder.appName("MarksConcatenation").getOrCreate()

# 构建示例DataFrame
data = [
    (2, 3, 3, 2, "PACKAGING MARKS 3"),
    (2, 3, 3, 1, "PACKAGING MARKS 2"),
    (2, 3, 3, 0, "PACKAGING MARKS 1"),
    (2, 4, 4, 2, "PACKAGING MARKS 23"),
    (2, 4, 4, 1, "PACKAGING MARKS 22"),
    (2, 4, 4, 0, "PACKAGING MARKS 21")
]
columns = ["mid", "marksId", "id", "index", "marks"]
df = spark.createDataFrame(data, schema=columns)

# 按mid和index升序排序(确保marks按index顺序拼接)
sorted_df = df.orderBy("mid", asc("index"))

# 分组并拼接marks字段
result_df = sorted_df.groupBy("mid") \
                     .agg(concat_ws("|", collect_list("marks")).alias("concatenated_marks"))

# 输出结果
result_df.show(truncate=False)

关键函数说明

  • collect_list("marks"):将同一mid分组下的所有marks值收集为一个列表
  • concat_ws("|", ...):指定竖线为分隔符,把列表中的字符串拼接成完整的单字符串

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 16:24:14