Pyspark 将标准列表转换为数据框
Pyspark convert a standard list to data frame
案例非常简单,我需要使用以下代码将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()
失败并出现以下错误:
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'>
请看下面的代码:
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()
df
+-------+
|numbers|
+-------+
| 1|
| 2|
| 3|
| 4|
+-------+
这个解决方案也是一种使用更少代码的方法,避免序列化为 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()
注意:关于命名变量 list
:术语 list
是一个 Python 内置函数,因此,强烈建议我们避免使用内置名称作为 name/label 用于我们的变量,因为我们最终会覆盖 list()
函数之类的东西。当快速而肮脏地制作原型时,许多人使用类似的东西:mylist
.
案例非常简单,我需要使用以下代码将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()
失败并出现以下错误:
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'>
请看下面的代码:
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()
df
+-------+
|numbers|
+-------+
| 1|
| 2|
| 3|
| 4|
+-------+
这个解决方案也是一种使用更少代码的方法,避免序列化为 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()
注意:关于命名变量 list
:术语 list
是一个 Python 内置函数,因此,强烈建议我们避免使用内置名称作为 name/label 用于我们的变量,因为我们最终会覆盖 list()
函数之类的东西。当快速而肮脏地制作原型时,许多人使用类似的东西:mylist
.