gpt4 book ai didi

python - PySpark 无法将字典的 RDD 转换为 DataFrame。错误 : can not accept object in type

转载 作者:太空宇宙 更新时间:2023-11-03 10:55:57 24 4
gpt4 key购买 nike

我目前使用的是 Spark 1.4.1,无法将带有嵌套字典的字典转换为 Spark DataFrame。我将嵌套的 dict 转换为 Row,但它似乎不接受我的模式。

这是重现我的错误的代码:

from pyspark.sql import Row, SQLContext, types as pst
sqlContext = SQLContext(sc)

example_dict = Row(**{"name": "Mike", "data": Row(**{"age": 10, "like": True})})

example_rdd = sc.parallelize([example_dict])

nested_fields = [pst.StructField("age", pst.IntegerType(), True),
pst.StructField("like", pst.BooleanType(), True)]

schema = pst.StructType([
pst.StructField("data", pst.StructType(nested_fields), True),
pst.StructField("name", pst.StringType(), True)
])

df = sqlContext.createDataFrame(example_rdd, schema)

TypeError: StructType(List(StructField(age,IntegerType,true),StructField(like,BooleanType,true))) can not accept object in type <class 'pyspark.sql.types.Row'>

我不确定为什么会收到此错误。以下是对象 rddschema:

>>> example_rdd.first()
Row(data=Row(age=10, like=True), name='Mike')

>>> schema
StructType(List(StructField(data,StructType(List(StructField(age,IntegerType,true),StructField(like,BooleanType,true))),true),StructField(name,StringType,true)))

我不确定我是否遗漏了什么,但模式似乎与对象匹配。 Spark 1.4.1 不接受行内行有什么原因吗?

请注意:这在 Spark 2.0.2 中不是问题,但不幸的是我在使用 Spark 1.4.1 的共享资源上,所以我需要暂时找到解决方法:(。任何帮助将不胜感激,在此先感谢!

最佳答案

发生这种情况是因为 Row 在 Spark 1.4 中不被接受为 StructType。接受的类型是:

pst._acceptable_types[pst.StructType]
(tuple, list)

Spark 进行简单检查:

type(obj) not in _acceptable_types[_type]

这显然不适用于 Row 对象。正确的条件,相当于当前版本中发生的情况,将是:

isinstance(obj, _acceptable_types[_type])

如果你想使用嵌套列,你可以使用普通的 Python tuple:

Row(**{"name": "Mike", "data": (10, True)})

((10, True), "Mike")

关于python - PySpark 无法将字典的 RDD 转换为 DataFrame。错误 : can not accept object in type <class 'pyspark.sql.types.Row' >,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40819434/

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