簡體   English   中英

如何在Spark SQL中從列表創建數據框?

[英]How to create dataframe from list in Spark SQL?

Spark版本:2.1

例如,在pyspark中,我創建一個列表

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

那么如何從test_list創建一個數據框,其中數據框的類型如下所示:

DataFrame[words: array<string>]

這是怎么做的 -

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) 

我不得不使用多個列和類型 - 下面的示例有一個字符串列和一個整數列。 對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|
+---------+-----+

您應該使用Row對象列表([Row])來創建數據框。

from pyspark.sql import Row

spark.createDataFrame(list(map(lambda x: Row(words=x), test_list)))
   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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM