通过列 [PySpark] 连接两个 DataFrame

Posted

技术标签:

【中文标题】通过列 [PySpark] 连接两个 DataFrame【英文标题】:Concatenate two DataFrames via column [PySpark] 【发布时间】:2018-03-16 14:12:15 【问题描述】:

我有两列,即(每列都有相同数量的条目)

df1 =
+-------+
| col1  |
+-------+
|   10  |
+-------+
|   3   |
+-------+
...
df2 = 
+-------+
| col2  |
+-------+
|   6   |
+-------+
|   1   |
+-------+
...

我希望合并它们,使最终的 DataFrame 具有以下形状:

df3 =
+-------+-------+
| col1  | col2  |
+-------+-------+
| 10    | 6     |
+-------+-------+
| 3     | 1     |
+-------+-------+
...

但我无法使用 join 方法来执行此操作,因为我没有尝试基于列标题合并列。如果有人对如何轻松实现这一点有任何提示,那将非常有帮助!

【问题讨论】:

检查这个,forums.databricks.com/questions/8180/… 您可能对此感兴趣 - ***.com/questions/45883151/… 【参考方案1】:

试试这个

df1 = df1.withColumn("code", monotonically_increasing_id())

df2 = df2.withColumn("code", monotonically_increasing_id())

这样你给他们两个列code,你可以用它来经典地合并两个df。

df3 = df2.join(df1, ["code"])

【讨论】:

以上是关于通过列 [PySpark] 连接两个 DataFrame的主要内容,如果未能解决你的问题,请参考以下文章