Подтвердить что ты не робот

Как создать DataFrame из списка в Spark SQL?

Искры версии: 2.1

Например, в pyspark я создаю список

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

то как создать DataFrame формы test_list, где тип данных данных выглядит следующим образом:

DataFrame[words: array<string>]

4b9b3361

Ответ 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) 

Ответ 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|
+---------+-----+

Ответ 3

Вы должны использовать список объектов Row ([Row]) для создания фрейма данных.

from pyspark.sql import Row

spark.createDataFrame(list(map(lambda x: Row(words=x), test_list)))

Ответ 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>