代码之家  ›  专栏  ›  技术社区  ›  L Z

是否可以使用PySpark创建元组类型的StructField?

  •  2
  • L Z  · 技术社区  · 6 年前

    我需要为Spark中的数据帧创建一个模式。创建常规 StructFields 例如 StringType ,则, IntegerType 。但是,我想创建一个 StructField 对于元组。

    我尝试了以下方法:

    StructType([
                 StructField("dst_ip", StringType()),
                 StructField("port", StringType())
               ])
    

    但是,它会抛出一个错误

    “列表对象没有属性‘name’”

    是否可以为元组类型创建StructField?

    2 回复  |  直到 4 年前
        1
  •  3
  •   pault Tanjin    6 年前

    您可以定义 StructType a的内部 StructField :

    schema = StructType(
        [
            StructField(
                "myTuple",
                StructType(
                    [
                        StructField("dst_ip", StringType()),
                        StructField("port", StringType())
                    ]
                )
            )
        ]
    )
    
    df = sqlCtx.createDataFrame([], schema)
    df.printSchema()
    #root
    # |-- myTuple: struct (nullable = true)
    # |    |-- dst_ip: string (nullable = true)
    # |    |-- port: string (nullable = true)
    
        2
  •  0
  •   user2314737    4 年前

    班级 StructType --用于定义数据帧的结构——是表示 Row 它包括 列表 属于 StructField 's。

    为了定义列的元组数据类型(例如 columnA )您需要封装(列出) 结构类型 将元组元素的 StructField结构域 .请注意 StructField结构域 s需要有名称,因为它们代表列。

    定义元组 StructField结构域 作为一个新的 结构类型 :

    columnA = StructField('columnA', StructType([
                                                  StructField("dst_ip", StringType()),
                                                  StructField("port", StringType())
                                                 ])
                         )
    

    定义架构包含 列A columnB (属于类型 FloatType ):

    mySchema = StructType([ columnA, StructField("columnB", FloatType())])
    

    将架构应用于数据帧:

    data =[{'columnA': ('x', 'y'), 'columnB': 1.0}] 
    # data = [Row(columnA=('x', 'y'), columnB=1.0)] (needs from pyspark.sql import Row)
    df = spark.createDataFrame(data, mySchema)
    df.printSchema()
    # root
    #  |-- columnA: struct (nullable = true)
    #  |    |-- dst_ip: string (nullable = true)
    #  |    |-- port: string (nullable = true)
    #  |-- columnB: float (nullable = true)
    

    显示数据帧:

    df.show()                                                                                 
    # +-------+-------+
    # |columnA|columnB|
    # +-------+-------+
    # | [x, y]|    1.0|
    # +-------+-------+
    

    (这只是 the other answer )