SyntaxError:使用ArrayType创建DataFrame时语法无效

时间:2018-09-06 08:51:08

标签: python python-3.x pyspark apache-spark-sql

我想创建PySpark DataFrame

from pyspark.sql import SparkSession
from pyspark.sql.types import *
from pyspark.sql import Row

spark = SparkSession \
    .builder \
    .appName("Test") \
    .master("local[4]") \
    .getOrCreate()

schema = StructType([StructField('id', StringType()), \
                     StructField('timestamp',LongType()), \
                     StructField('coordinates',ArrayType())])
rows = [Row(id="11", timestamp=1523975430000, coordinates = [41.5555, 2.1522])]

df = spark.createDataFrame(rows, schema)

但是,我在SyntaxError: invalid syntax旁收到语法错误lat。我假设ArrayType对象应该以不同的方式创建。 有人可以帮助我创建此DataFrame df吗?

更新

预期结果:

id    timestamp       coordinates
11    1523975430000    [41.5555, 2.1522]

1 个答案:

答案 0 :(得分:1)

ArrayType需要元素的类型。试试:

schema = StructType([StructField('id', StringType()), \
                     StructField('timestamp',LongType()), \
                     StructField('coordinates',ArrayType(DoubleType()))])
rows = [Row(id="11", timestamp=1523975430000, coordinates = [ 41.5555,  2.1522])]

结果:

+---+-------------+-----------------+
| id|    timestamp|      coordinates|
+---+-------------+-----------------+
| 11|1523975430000|[41.5555, 2.1522]|
+---+-------------+-----------------+