Mar*_*kus 3 scala dataframe apache-spark
我有两个数据帧(Spark 2.2.0 和 Scala 2.11.8)。第一个 DataFramedf1有一列称为col1,第二个df2也有 1 列称为col2。两个 DataFrame 中的行数相等。
如何将这两列合并到一个新的 DataFrame 中?
我试过了join,但我认为应该有其他方法来做到这一点。
另外,我尝试应用withColumm,但它无法编译。
val result = df1.withColumn(col("col2"), df2.col1)
Run Code Online (Sandbox Code Playgroud)
更新:
例如:
df1 =
col1
1
2
3
df2 =
col2
4
5
6
result =
col1 col2
1 4
2 5
3 6
Run Code Online (Sandbox Code Playgroud)
如果这两列之间没有实际关系,听起来您需要联合运算符,它将返回,好吧,只是这两个数据帧的联合:
var df1 = Seq("a", "b", "c").toDF("one")
var df2 = Seq("d", "e", "f").toDF("two")
df1.union(df2).show
+---+
|one|
+---+
| a |
| b |
| c |
| d |
| e |
| f |
+---+
Run Code Online (Sandbox Code Playgroud)
[编辑] 现在您已经明确表示只需要两列,然后使用 DataFrames,您可以使用函数 monotonically_increasing_id() 添加行索引并加入该索引值的技巧:
import org.apache.spark.sql.functions.monotonically_increasing_id
var df1 = Seq("a", "b", "c").toDF("one")
var df2 = Seq("d", "e", "f").toDF("two")
df1.withColumn("id", monotonically_increasing_id())
.join(df2.withColumn("id", monotonically_increasing_id()), Seq("id"))
.drop("id")
.show
+---+---+
|one|two|
+---+---+
| a | d |
| b | e |
| c | f |
+---+---+
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3933 次 |
| 最近记录: |