首页 > 解决方案 > 无法在 PySpark 中创建数据框

问题描述

我想使用以下代码在 PySpark 中创建一个数据框

from pyspark.sql import *
from pyspark.sql.types import *

temp = Row("DESC", "ID")
temp1 = temp('Description1323', 123)

print temp1

schema = StructType([StructField("DESC", StringType(), False),
                     StructField("ID", IntegerType(), False)])

df = spark.createDataFrame(temp1, schema)

但我收到以下错误:

TypeError:StructType 不能接受类型“str”中的对象“Description1323”

我的代码有什么问题?

标签: pythonapache-sparkpysparkdatabricks

解决方案


问题是你正在传递一个Row你应该传递一个Rows列表的地方。尝试这个:

from pyspark.sql import *
from pyspark.sql.types import *

temp = Row("DESC", "ID")
temp1 = temp('Description1323', 123)

print temp1

schema = StructType([StructField("DESC", StringType(), False),
                     StructField("ID", IntegerType(), False)])

df = spark.createDataFrame([temp1], schema)

df.show()

结果:

+---------------+---+
|           DESC| ID|
+---------------+---+
|Description1323|123|
+---------------+---+

推荐阅读