PySpark:如何将一列再联接到数据帧



我正在处理一个具有两个初始列的数据帧,idcolA

+---+-----+
|id |colA |
+---+-----+
| 1 |  5  |
| 2 |  9  |
| 3 |  3  |
| 4 |  1  |
+---+-----+

我需要将该数据帧合并到另一列,colB。我知道colB非常适合数据帧的末尾,我只需要一些方法将它们连接在一起。

+-----+
|colB |
+-----+
|  8  |
|  7  | 
|  0  | 
|  6  |
+-----+

因此,我需要获取如下所示的新数据帧:

+---+-----+-----+
|id |colA |colB |
+---+-----+-----+
| 1 |  5  | 8   |
| 2 |  9  | 7   |
| 3 |  3  | 0   |
| 4 |  1  | 6   |
+---+-----+-----+

这是获取第一个数据帧的 pyspark 代码:

l=[(1,5),(2,9), (3,3), (4,1)]
names=["id","colA"]
db=sqlContext.createDataFrame(l,names)
db.show()

我该怎么做?有人可以帮我吗?谢谢

我已经完成了!我已经通过添加一个带有行索引的临时列来解决它,然后删除它。

法典:

from pyspark.sql import Row
from pyspark.sql.window import Window
from pyspark.sql.functions import rowNumber
w = Window().orderBy()
l=[(1,5),(2,9), (3,3), (4,1)]
names=["id","colA"]
db=sqlContext.createDataFrame(l,names)
db.show()
l=[5,9,3,1]
rdd = sc.parallelize(l).map(lambda x: Row(x))
test_df = rdd.toDF()
test_df2 =  test_df.selectExpr("_1 as colB")
dbB = test_df2.select("colB")
db= db.withColum("columnindex", rowNumber().over(w))
dbB = dbB.withColum("columnindex", rowNumber().over(w))

testdf_out = db.join(dbB, db.columnindex == dbB.columnindex. 'inner').drop(db.columnindex).drop(dbB.columnindex)
testdf_out.show()

最新更新