首页 文章

Pyspark将标准列表转换为数据框[重复]

提问于
浏览
8

这个问题在这里已有答案:

这种情况非常简单,我需要使用以下代码将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'>

2 回答

  • 6

    此解决方案也是一种使用较少代码的方法,避免了对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内置函数,因此,强烈建议我们避免使用内置名称作为变量的名称/标签,因为我们最终会覆盖 list() 函数之类的东西 . 当快速和肮脏的原型,许多人使用类似的东西: mylist .

  • 6

    请参阅以下代码:

    from pyspark.sql import Row
        li=[1,2,3,4]
        rdd1 = sc.parallelize(li)
        row_rdd = rdd1.map(lambda x: Row(x))
        df=sqlContext.createDataFrame(row_rdd,['numbers']).show()
    

    df

    +-------+
    |numbers|
    +-------+
    |      1|
    |      2|
    |      3|
    |      4|
    +-------+
    

相关问题