【问题标题】:Spark SQL SchemaSpark SQL 模式
【发布时间】:2017-06-14 22:47:07
【问题描述】:

我在 PySpark 中有这个 RDD,我想创建架构。

收集的 1 行 RDD 示例:

(('16/12/2006', '17:24:00', 4.216, 0.418, 234.84, 18.4, 0.0, 1.0, 17.0), 0)
customSchema = StructType([
    StructField("Date", StringType(), True),
    StructField("Hour", StringType(), True),
    StructField("ActivePower", FloatType(), True),
    StructField("ReactivePower", FloatType(), True),
    StructField("Voltage", FloatType(), True),
    StructField("Instensity", FloatType(), True),
    StructField("Sub1", FloatType(), True),
    StructField("Sub2", FloatType(), True),
    StructField("Sub3", FloatType(), True),
    StructField("ID", IntegerType(), True)])

问题是索引(最后一个零)不在数据元组中,我不知道如何正确制作架构。

提前谢谢你。

【问题讨论】:

    标签: sql apache-spark pyspark schema


    【解决方案1】:

    你快到了。你只需要另一个StructField

    data = [
        (('16/12/2006', '17:24:00', 4.216, 0.418, 234.84, 18.4, 0.0, 1.0, 17.0), 0)
    ]
    
    schema = StructType([
        StructField("values", StructType([
            StructField("Date", StringType(), True),
            StructField("Hour", StringType(), True),
            StructField("ActivePower", FloatType(), True),
            StructField("ReactivePower", FloatType(), True),
            StructField("Voltage", FloatType(), True),
            StructField("Instensity", FloatType(), True),
            StructField("Sub1", FloatType(), True),
            StructField("Sub2", FloatType(), True),
            StructField("Sub3", FloatType(), True),
        ])),
        StructField("ID", IntegerType(), True)
    ])
    
    
    df = spark.createDataFrame(data, schema)
    
    df.printSchema()
    
    root
     |-- values: struct (nullable = true)
     |    |-- Date: string (nullable = true)
     |    |-- Hour: string (nullable = true)
     |    |-- ActivePower: float (nullable = true)
     |    |-- ReactivePower: float (nullable = true)
     |    |-- Voltage: float (nullable = true)
     |    |-- Instensity: float (nullable = true)
     |    |-- Sub1: float (nullable = true)
     |    |-- Sub2: float (nullable = true)
     |    |-- Sub3: float (nullable = true)
     |-- ID: integer (nullable = true)
    
    df.show(1, False)
    
    +----------------------------------------------------------+---+
    |values                                                    |ID |
    +----------------------------------------------------------+---+
    |[16/12/2006,17:24:00,4.216,0.418,234.84,18.4,0.0,1.0,17.0]|0  |
    +----------------------------------------------------------+---+
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-31
      • 2018-03-25
      • 2015-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-29
      • 2021-05-28
      相关资源
      最近更新 更多