【发布时间】: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
Spark 版本:2.1
例如,在pyspark中,我创建了一个列表
test_list = [['Hello', 'world'], ['I', 'am', 'fine']]
那么如何从test_list创建一个dataframe,其中dataframe的类型如下:
DataFrame[words: array<string>]
【问题讨论】:
标签: python apache-spark pyspark
这里是-
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)
【讨论】:
from ... import *(在 Python 中几乎被普遍认为是一种反模式)在这里是可取的?
我必须使用多个列和类型 - 下面的示例有一个字符串列和一个整数列。对 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 中几乎被普遍认为是一种反模式)在这里是可取的?
您应该使用 Row 对象列表([Row])来创建数据框。
from pyspark.sql import Row
spark.createDataFrame(list(map(lambda x: Row(words=x), test_list)))
【讨论】:
spark.createDataFrame
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>
【讨论】:
pyspark。