【问题标题】:Pyspark transform key-value pairs into columnsPyspark 将键值对转换为列
【发布时间】:2021-05-28 15:40:18
【问题描述】:

我有一个 json 文件,其中包含如下所示的数据:

"Url": "https://sample.com", "Method": "POST", "Headers": [{"Key": "accesstoken", "Value": ["123"]}, {"Key": "id", "Value": ["abc"]}, {"Key": "context", "Value": ["sample"]}]

在读取 json 时,我将架构明确定义为:

schema = StructType(
    [
      StructField('Url', StringType(), True),
      StructField('Method', StringType(), True),
      StructField("Headers",ArrayType(StructType([
        StructField('Key', StringType(), True),
        StructField("Value",ArrayType(StringType()),True),
      ]),True),True)
    ]
  )

目标是将键值数据作为列而不是行来读取。

Url Method accesstoken id context
https://sample.com POST 123 abc sample

分解“标题”列只会将其转换为多行。数据的另一个问题是,我的键值对值存储在 2 个单独的对中,而不是文字键值对(例如“accesstoken”:“123”)!

我尝试遍历这些值以首先创建地图,但我无法遍历“标题”列。

df_map = df.withColumn('map', to_json(array(*[create_map(element.Key, element.Value) for element in df.Headers])))

我还尝试将“标题”列读取为 MapType(StringType, ArrayType(StringType)),但它无法读取该值。当我这样做时它显示为 null。

有没有办法做到这一点?我是否必须以纯文本形式读取数据并预处理数据而不是数据框?

【问题讨论】:

    标签: apache-spark pyspark apache-spark-sql key-value


    【解决方案1】:

    您的方法是正确的,但要连接您的地图必须使用reduce 表达式:

    from pyspark.sql.types import *
    import pyspark.sql.functions as f
    
    # [...] Your dataframe initialization
    
    df = df.select('Url', 'Method', f.explode(f.expr('REDUCE(Headers, cast(map() as map<string, array<string>>), (acc, el) -> map_concat(acc, map(el.Key, el.Value)))')))
    
    # Transform key:value into columns
    df_pivot = (df
                .groupBy('Url', 'Method')
                .pivot('key')
                .agg(f.first('value')))
    
    array_columns = [column for column, _type in df_pivot.dtypes if _type.startswith('array')]
    df_pivot = (df_pivot
                .withColumn('zip', f.explode(f.arrays_zip(*array_columns)))
                .select('Url', 'Method', 'zip.*'))
    
    df_pivot.show(truncate=False)
    

    输出

    +------------------+------+-----------+-------+---+
    |Url               |Method|accesstoken|context|id |
    +------------------+------+-----------+-------+---+
    |https://sample.com|POST  |123        |sample |abc|
    +------------------+------+-----------+-------+---+
    

    【讨论】:

      猜你喜欢
      • 2016-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-24
      • 2019-05-19
      • 2018-02-20
      • 2021-10-09
      • 2021-04-18
      相关资源
      最近更新 更多