Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Pyspark-withColumn在调用空数据帧时不工作_Python_Pyspark - Fatal编程技术网

Python Pyspark-withColumn在调用空数据帧时不工作

Python Pyspark-withColumn在调用空数据帧时不工作,python,pyspark,Python,Pyspark,我为一些需求创建了一个空的数据框,当我调用它的withColumn函数时,我得到了列,但是数据是空的,如下所示- schema = StructType([]) df = sqlContext.createDataFrame(sc.emptyRDD(), schema) json = list(map(lambda row: row.asDict(True), df.collect())) df.show() ++ || ++ ++ df= df.withColumn('First_name

我为一些需求创建了一个空的数据框,当我调用它的withColumn函数时,我得到了列,但是数据是空的,如下所示-

schema = StructType([])
df = sqlContext.createDataFrame(sc.emptyRDD(), schema)
json = list(map(lambda row: row.asDict(True), df.collect()))
df.show()

++
||
++
++

df= df.withColumn('First_name',F.lit('Tony'))\
                    .withColumn('Last_name',F.lit('Chapman'))\
                .withColumn('Age',F.lit('28'))
df.show()

+----------+---------+---+
|First_name|Last_name|Age|
+----------+---------+---+
+----------+---------+---+

这是什么原因?如何解决这个问题?

这是预期的结果-withColumn意味着spark将迭代所有行,然后向每行添加一列。因为您的数据帧是空的,所以没有任何值可以迭代

如果要将一些数据放入数据帧中,则需要使用parallelize

from pyspark.sql import Row
l = [('Tony','Chapman',28)]
rdd = sc.parallelize(l)
rdd_rows = rdd.map(lambda x: Row(First_Name=x[0],Last_Name=x[1] Age=int(x[2])))
df = sqlContext.createDataFrame(rdd_rows)
或者从Spark 2.0(谢谢pault)中,您可以跳过rdd创建

l = [('Tony','Chapman',28)]
df = sqlContext.createDataFrame(l, ["First_Name", "Last_Name", "Age"]

@pault,抱歉为我正在处理的其他df提供了输出。我现在编辑了这个问题。请看一看谢谢,这就是我要找的…在您可以跳过
parallelize
部分之前,我对withColumn没有这样的了解:
df=sqlContext.createDataFrame(l,[“First\u Name”、“Last\u Name”、“Age”])
。你也看到了吗