gpt4 book ai didi

unicode - 来自带有模式的行的 sqlContext.createDataframe。 pyspark : TypeError: IntegerType can not accept object in type

转载 作者:行者123 更新时间:2023-12-02 03:20:52 25 4
gpt4 key购买 nike

在花了很多时间弄清楚为什么会出现以下错误之后

pyspark: TypeError: IntegerType can not accept object in type <type 'unicode'>

在尝试基于行和架构创建数据框时,我注意到以下几点:

在我的 rdd 中有一个名为 rrdRows 的行,如下所示:

Row(a="1", b="2", c=3)

我的 dfSchema 定义为:

dfSchema = StructType([
StructField("c", IntegerType(), True),
StructField("a", StringType(), True),
StructField("b", StringType(), True)
])

按如下方式创建数据框:

df = sqlContext.createDataFrame(rddRows, dfSchema)

会出现上面提到的错误,因为Spark只考虑了StructFields在schema中的顺序,并没有将StructFields的名称与Row字段的名称匹配。

换句话说,在上面的示例中,我注意到 spark 试图创建一个如下所示的数据框(如果没有 typeError.e.x,如果所有内容都是 String 类型的话)

+---+---+---+
| c | b | a |
+---+---+---+
| 1 | 2 | 3 |
+---+---+---+

这真的是预期的,还是某种错误?

编辑:rddRows 是按照这些线创建的:

def createRows(dic):
res = Row(a=dic["a"],b=dic["b"],c=int(dic["c"])
return res

rddRows = rddDict.map(createRows)

其中 rddDict 是已解析的 JSON 文件。

最佳答案

如果您提供关键字参数,Row 的构造函数会对键进行排序。看看源码here .当我发现这一点时,我最终在将它应用于数据框之前相应地对我的 schema 进行了排序:

   sorted_fields = sorted(dfSchema.fields, key=lambda x: x.name)
sorted_schema = StructType(fields=sorted_fields)
df = sqlContext.createDataFrame(rddRows, sorted_schema)

关于unicode - 来自带有模式的行的 sqlContext.createDataframe。 pyspark : TypeError: IntegerType can not accept object in type <type 'unicode' >,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33500137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com