【问题标题】:How to create dataframe from list in Spark SQL?如何从 Spark SQL 中的列表创建数据框?
【发布时间】:2017-09-12 16:25:25
【问题描述】:

Spark 版本:2.1

例如,在pyspark中,我创建了一个列表

test_list = [['Hello', 'world'], ['I', 'am', 'fine']]

那么如何从test_list创建一个dataframe,其中dataframe的类型如下:

DataFrame[words: array<string>]

【问题讨论】:

    标签: python apache-spark pyspark


    【解决方案1】:

    这里是-

    from pyspark.sql.types import *
    
    cSchema = StructType([StructField("WordList", ArrayType(StringType()))])
    
    # notice extra square brackets around each element of list 
    test_list = [['Hello', 'world']], [['I', 'am', 'fine']]
    
    df = spark.createDataFrame(test_list,schema=cSchema) 
    

    【讨论】:

    • 对于任何只想转换字符串列表并且对缺乏适当文档的荒谬印象深刻的人:您无法转换一维对象,您必须将其转换为元组列表,例如:[( t,) for t in list_of_strings]
    • 为什么from ... import *(在 Python 中几乎被普遍认为是一种反模式)在这里是可取的?
    • 感谢@Timomo,这有帮助。
    【解决方案2】:

    我必须使用多个列和类型 - 下面的示例有一个字符串列和一个整数列。对 Pushkr 的代码(上图)稍作调整:

    from pyspark.sql.types import *
    
    cSchema = StructType([StructField("Words", StringType())\
                          ,StructField("total", IntegerType())])
    
    test_list = [['Hello', 1], ['I am fine', 3]]
    
    df = spark.createDataFrame(test_list,schema=cSchema) 
    

    输出:

     df.show()
     +---------+-----+
    |    Words|total|
    +---------+-----+
    |    Hello|    1|
    |I am fine|    3|
    +---------+-----+
    

    【讨论】:

    • 我在另一个答案上问过同样的问题:为什么from ... import *(在 Python 中几乎被普遍认为是一种反模式)在这里是可取的?
    【解决方案3】:

    您应该使用 Row 对象列表([Row])来创建数据框。

    from pyspark.sql import Row
    
    spark.createDataFrame(list(map(lambda x: Row(words=x), test_list)))
    

    【讨论】:

    • 应该是spark.createDataFrame
    【解决方案4】:
       You can create a RDD first from the input and then convert to dataframe from the constructed RDD
       <code>  
         import sqlContext.implicits._
           val testList = Array(Array("Hello", "world"), Array("I", "am", "fine"))
           // CREATE RDD
           val testListRDD = sc.parallelize(testList)
         val flatTestListRDD = testListRDD.flatMap(entry => entry)
         // COnvert RDD to DF 
         val testListDF = flatTestListRDD.toDF
         testListDF.show
        </code> 
    

    【讨论】:

    • 这似乎是 Scala 代码而不是 Python,对于任何想知道为什么这被否决的人来说。该问题已明确标记为pyspark
    猜你喜欢
    • 2019-07-11
    • 2016-11-17
    • 1970-01-01
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-01
    相关资源
    最近更新 更多