代码之家  ›  专栏  ›  技术社区  ›  ZygD

如何链分解和结构字段选择?

  •  0
  • ZygD  · 技术社区  · 4 年前

    数据帧:

    from pyspark.sql import functions as F
    df = spark.createDataFrame([([(1, 2), (3, 4)],)], 'col_name array<struct<c1:int,c2:int>>')
    
    df.show()
    # +----------------+
    # |        col_name|
    # +----------------+
    # |[{1, 2}, {3, 4}]|
    # +----------------+
    
    df.printSchema()
    # root
    #  |-- col_name: array (nullable = true)
    #  |    |-- element: struct (containsNull = true)
    #  |    |    |-- c1: integer (nullable = true)
    #  |    |    |-- c2: integer (nullable = true)
    

    explode 数组(结果是类型为的列 struct<c1:int,c2:int> )。
    然后选择每个结构字段 (但是我 select 两次) :

    df = df.select(
        F.explode('col_name')
    ).select(
        [f'col.{c}' for c in ('c1', 'c2')]
    )
    
    df.show()
    # +---+---+
    # | c1| c2|
    # +---+---+
    # |  1|  2|
    # |  3|  4|
    # +---+---+
    
    df.printSchema()
    # root
    #  |-- c1: integer (nullable = true)
    #  |-- c2: integer (nullable = true)
    

    我知道我可以将第二个选择缩短为 'col.*' 。但我仍然有两个选择。

    问题 是否有选择结构字段的方法 爆炸后 只有1个选择?

    作为分解的结果,有架构 结构<c1:int,c2:int> ,我以为这会奏效。。。

    df = df.select(
        [F.explode('col_name')[c] for c in ('c1', 'c2')]
    )
    

    AnalysisException:col中没有这样的结构字段c1

    0 回复  |  直到 4 年前
        1
  •  1
  •   wwnde    4 年前

    使用魔术内联

    df.selectExpr('inline(col_name)').show()
    
    +---+---+
    | c1| c2|
    +---+---+
    |  1|  2|
    |  3|  4|
    +---+---+