python - 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')
没有奏效,也没有找到任何有关如何操作的信息。
解决方案
这是因为我的 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)
])
这是正确的架构。
推荐阅读
- signals - 不能在 OCTAVE 中进行 amdemod
- google-apps-script - Google 脚本 - 将值复制到新工作表中,已存在的值除外
- python - 匹配两个 .xlsx 文件中的唯一列,如果匹配更新,则使用 openpyxl 追加
- java - java中静态变量的混淆
- app-inventor - App Inventor 2 特殊字符,用于在加入文本时添加“空格”字符
- excel - Excel 将不同工作簿中的数据复制到 1 个工作簿中
- javascript - 在 Next.js 中模仿 react-router-dom 嵌套路由
- arrays - Svelte 输入绑定 JSON 数组
- cmd - MSI 安装程序抛出退出代码 3010 并且无法修复它。需要帮助
- angularjs - 未捕获的错误:Angular JS 中的 [$injector:modulerr] 和 ngRoute 错误