首页 > 解决方案 > Pyspark - 从具有数组字段的列表列表创建 DataFrame

问题描述

我想加载一些示例数据,因为它包含一个数组字段,所以我不能简单地将其保存为 CSV 并加载 CSV 文件。

from pyspark.sql.types import *

sample_data = [["prasad, jones",120,"M",[170,50],"brown","1999-10-15T19:50:23+00:00",34,0.1],
["maurice, khan",82,"M",[130,30],"blond","1988-02-01T19:50:23+00:00",67,0.32]]

customSchema = StructType([
  StructField("name", StringType(), True),
  StructField("income", IntegerType(), True),
  StructField("gender", StringType(), True),
  StructField("height_weight", ArrayType(
      StructType([
          StructField("height", IntegerType(), True),
          StructField("weight", IntegerType(), True)
      ]))),
  StructField("hair-color", StringType(), True),
  StructField("dateofbirth", TimestampType(), True),
  StructField("factorX", DoubleType(), True),
  StructField("factorY", DoubleType(), True)
])

# Try #1
df1 = spark.createDataFrame(sample_data,schema=customSchema)
# Try #2
df2 = spark.createDataFrame(spark.sparkContext.parallelize(sample_data),schema=customSchema) 

正如其他类似问题/答案所建议的那样,我尝试简单地创建一个数据框,或者在加载它之前对其进行并行化,但我不断收到以下错误:

TypeError: element in array field height_weight: StructType can not accept object 130 in type <class 'int'>

我错过了什么?或者,加载这些数据的更简单方法是什么?我尝试了一个制表符分隔的文本文件,但spark.read.format('txt')没有奏效,也没有找到任何有关如何操作的信息。

标签: pythonapache-sparkpysparkapache-spark-sql

解决方案


这是因为我的 ArrayType 定义错误。它是整数数组 [int,int],而不是具有整数数组 [[int],[int]] 的数组。

    customSchema = StructType([
  StructField("name", StringType(), True),
  StructField("income", IntegerType(), True),
  StructField("gender", StringType(), True),
  StructField("height_weight", ArrayType(IntegerType()), True),
  StructField("hair-color", StringType(), True),
  StructField("dateofbirth", StringType(), True),
  StructField("factorX", IntegerType(), True),
  StructField("factorY", DoubleType(), True)
])

这是正确的架构。


推荐阅读