Pyspark中未确定的类型错误

时间:2017-09-25 10:53:29

标签: pyspark spark-dataframe

我有一个要求,其中我必须将字典转换为数据帧,下面是字典:

{'col1': None, 'product_volume_override': '1', 'col2': '70', 'col3': None},{'col1': None, 'col2': '1', 'col3': '70'}

以下是相同的火花代码:

spark_df = sc.parallelize([{'col1': None, 'col2': '70', 'col3': None},{'col1': None, 'col2': '1', 'col3': '70'}]).toDF()

然而,它向我抛出以下错误:

ValueError: Some of types cannot be determined by the first 100 rows, please try again with sampling

当所有记录的特定列值为空时,将出现此错误。

有人可以帮助我使用pyspark实现来处理这个问题吗?

1 个答案:

答案 0 :(得分:3)

为数据框定义架构,并对具有空值的列使用nullable=True

y = StructType([StructField("col1",StringType(), nullable = True), 
                StructField("col2",StringType(), nullable = True),
                StructField("col3",StringType(), nullable = True),
               StructField("col4",StringType(), nullable = True)])

现在将此架构提供给toDF()方法

spark_df = sc.parallelize([{'col1': None, 'col2': '70', 'col3': None},{'col1': None, 'col2': '1', 'col3': '70'}]).toDF(schema = y)
spark_df.show()
+----+----+----+----+
|col1|col2|col3|col4|
+----+----+----+----+
|null|  70|null|null|
|null|   1|  70|null|
+----+----+----+----+