【问题标题】:SyntaxError: invalid syntax when creating DataFrame with ArrayTypeSyntaxError:使用 ArrayType 创建 DataFrame 时语法无效
【发布时间】:2018-09-06 08:51:07
【问题描述】:

我想创建 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)

但是,lat 旁边出现语法错误 SyntaxError: invalid syntax。我假设应该以不同的方式创建 ArrayType 对象。 有人可以帮我创建这个 DataFrame df吗?

更新:

预期结果:

id    timestamp       coordinates
11    1523975430000    [41.5555, 2.1522]

【问题讨论】:

  • 您不能在列表内进行分配。
  • @timgeb:但是应该有一些方法可以将我的数据保存在 DataFrame 中,不是吗?
  • 在不知道您的数据框应该是什么样子的情况下无法回答。
  • @timgeb:查看我的更新,我在其中显示预期的 DataFrame。

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


【解决方案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]|
+---+-------------+-----------------+

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-19
    • 2018-12-14
    • 2020-07-30
    • 1970-01-01
    相关资源
    最近更新 更多