python - Pyspark 将标准列表转换为数据框

标签 python apache-spark pyspark pyspark-sql

<分区>

案例非常简单,我需要使用以下代码将 python 列表转换为数据框

from pyspark.sql.types import StructType
from pyspark.sql.types import StructField
from pyspark.sql.types import StringType, IntegerType

schema = StructType([StructField("value", IntegerType(), True)])
my_list = [1, 2, 3, 4]
rdd = sc.parallelize(my_list)
df = sqlContext.createDataFrame(rdd, schema)

df.show()

失败并出现以下错误:

    raise TypeError("StructType can not accept object %r in type %s" % (obj, type(obj)))
TypeError: StructType can not accept object 1 in type <class 'int'>

最佳答案

此解决方案也是一种使用较少代码、避免序列化为 RDD 并且可能更容易理解的方法:

from pyspark.sql.types import IntegerType

# notice the variable name (more below)
mylist = [1, 2, 3, 4]

# notice the parens after the type name
spark.createDataFrame(mylist, IntegerType()).show()

注意:关于命名您的变量list:术语list 是Python 内置函数,因此强烈建议我们避免使用内置名称作为名称/label 用于我们的变量,因为我们最终会覆盖诸如 list() 函数之类的东西。在快速而肮脏地制作原型(prototype)时,许多人会使用类似这样的东西:mylist

关于python - Pyspark 将标准列表转换为数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48448473/

相关文章:

apache-spark - 为什么sc.cassandraTable ("test", "users").select ("username") 的map函数不能用?

python - 如何获得在 Spark 1.5.2 中使用 HiveContext 制作的 PySpark DataFrame?

python - 使用 PySpark 读取 Excel 文件 : Failed to find data source: com. crealytics.spark.excel

apache-spark - pyspark 2.0 抛出 AlreadyExistsException(消息 :Database default already exists) when interact with hive

python - 以日期和第三个变量作为颜色的散点图

python - Celery 任务的定义和实现可以拆分吗?

python - 将一组数组从 python 输出保存到 csv 文件

apache-spark - 无法在 pyspark 中导入 lzo 文件

python - 我似乎无法让 Spark 上的 --py-files 工作

python - Django TestCase 测试顺序