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

PySpark:按列名后缀匹配列值并生成带匹配状态的DataFrame

PySpark 列匹配与状态标记实现方案

步骤1:提取并匹配orc/hive列对

先从原DataFrame的字段中拆分出orc开头和hive开头的列,再按第一个下划线后的后缀匹配对应列对:

# 筛选orc和hive开头的列
orc_cols = [col for col in df.columns if col.startswith('orc_')]
hive_cols = [col for col in df.columns if col.startswith('hive_')]

# 按后缀匹配列对,比如(orc_color, hive_color)
col_pairs = []
for orc_col in orc_cols:
    # 提取第一个下划线后的后缀
    suffix = orc_col.split('_', 1)[1]
    # 找到对应后缀的hive列
    matching_hive_col = next((h for h in hive_cols if h.split('_', 1)[1] == suffix), None)
    if matching_hive_col:
        col_pairs.append((orc_col, matching_hive_col))

步骤2:构造结果DataFrame

对每一对匹配的列,生成包含列名、对应值和匹配状态的行,最后合并所有行:

from pyspark.sql import functions as F
from pyspark.sql.types import StructType, StructField, StringType

# 定义结果表结构
result_schema = StructType([
    StructField("orc_columns", StringType(), True),
    StructField("orc_values", StringType(), True),
    StructField("hive_columns", StringType(), True),
    StructField("hive_values", StringType(), True),
    StructField("Status", StringType(), True)
])

# 初始化空结果表
result_df = spark.createDataFrame([], schema=result_schema)

for orc_col, hive_col in col_pairs:
    # 构造当前列对的行数据
    temp_df = df.select(
        F.lit(orc_col).alias("orc_columns"),
        F.col(orc_col).cast(StringType()).alias("orc_values"),
        F.lit(hive_col).alias("hive_columns"),
        F.col(hive_col).cast(StringType()).alias("hive_values"),
        # 判断值是否匹配,标记状态
        F.when(F.col(orc_col) == F.col(hive_col), "Matched").otherwise("Un_matched").alias("Status")
    )
    # 合并到结果表
    result_df = result_df.union(temp_df)

# 查看最终结果
result_df.show()

执行结果

运行后会输出符合要求的DataFrame:

+-----------+----------+------------+-----------+-----------+
|orc_columns|orc_values|hive_columns|hive_values|     Status|
+-----------+----------+------------+-----------+-----------+
| orc_color |       red|  hive_color|       blue| Un_matched|
| orc_numbr |         1|  hive_numbr|          1|    Matched|
+-----------+----------+------------+-----------+-----------+

注意事项

  • 使用split('_', 1)确保只拆分第一个下划线,兼容列名包含多个下划线的场景(如orc_color_code)。
  • 将值统一转为StringType,避免不同数据类型列对比时出现类型错误。
  • 支持原DataFrame有多行数据的场景,每行原数据都会生成对应数量的结果行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 04:46:20