【问题标题】:List of tuples PySpark SchemaPySpark Schema 元组列表
【发布时间】:2020-05-08 09:58:45
【问题描述】:

以下内容的正确 PySpark 架构是什么?第一个返回是一个列表,我已经正确编码,但第二个返回是一个元组列表,我不知道如何在一个模式中编写其对应的类型。

df = spark.createDataFrame([("Alive", 4)], ["Name", "Number"])


def example(n):
    return Row('Out1', 'Out2')([n + 2, n+4], [(n, n+2), (n, n+4)])


schema = StructType([
    StructField("Out1", ArrayType(IntegerType()), False),
    StructField("Out2", ArrayType(IntegerType(), False), True)])

example_udf = F.udf(example, schema)

newDF = df.withColumn("Output", F.explode(F.array(example_udf(df["Number"]))))
newDF = newDF.select("Name", "Number", "Output.*")

提前非常感谢!

【问题讨论】:

    标签: python pyspark schema


    【解决方案1】:

    感谢@Suresh!我的问题的另一个答案是:

    schema = StructType([
        StructField("Out1", ArrayType(IntegerType()), False),
        StructField("Out2", ArrayType(StructType([StructField("_1", IntegerType(), False), StructField("_2", IntegerType(), False)])))])
    
    

    【讨论】:

      【解决方案2】:

      我们可以使用第二个返回类型为array(array(integer))

      df = spark.createDataFrame([("Alive", 4)], ["Name", "Number"])
      def example(n):
          return ([n + 2, n+4], [(n, n+2), (n, n+4)])
      
      schema =StructType([StructField('out1',ArrayType(IntegerType())),StructField('out2',ArrayType(ArrayType(IntegerType())))])
      
      example_udf = F.udf(example, schema)
      
      df.select(example_udf(df.number).alias('s_col')).select('s_col.out1','s_col.out2').show()
      +------+--------------+
      | out1 |  out2        |
      +---+-----------------+
      |[6,8] |[[4,6],[4,8]] |
      +------+--------------+
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-01
        • 2016-05-02
        • 2019-02-14
        • 2014-02-01
        相关资源
        最近更新 更多