Pyspark将标准列表转换为数据框

sei*_*iya 18 python apache-spark pyspark pyspark-sql

这种情况非常简单,我需要使用以下代码将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()
Run Code Online (Sandbox Code Playgroud)

它失败并出现以下错误:

    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'>
Run Code Online (Sandbox Code Playgroud)

E. *_*eme 21

此解决方案也是一种使用较少代码的方法,避免了对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()
Run Code Online (Sandbox Code Playgroud)

注意:关于命名变量list:该术语list是Python内置函数,因此,强烈建议我们避免使用内置名称作为变量的名称/标签,因为我们最终会覆盖list()函数之类的东西.当快速和肮脏的原型,许多人使用如下:mylist.

  • 有没有办法为数据字段命名(在本例中默认为“值”) (4认同)
  • 好的答案,明确的答案。最后一行`.show()`使`df`保持`无`。 (2认同)
  • 有人尝试过使用数百万行吗?我做到了,但效果不是很好。 (2认同)

use*_*990 7

请参阅以下代码:

    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()
Run Code Online (Sandbox Code Playgroud)

DF

+-------+
|numbers|
+-------+
|      1|
|      2|
|      3|
|      4|
+-------+
Run Code Online (Sandbox Code Playgroud)