gpt4 book ai didi

scala - 如何将两列合并到一个新的 DataFrame 中?

转载 作者:行者123 更新时间:2023-12-02 08:10:35 28 4
gpt4 key购买 nike

我有两个 DataFrame(Spark 2.2.0 和 Scala 2.11.8)。第一个 DataFrame df1 有一个名为 col1 的列,第二个 df2 也有一个名为 col2 的列。两个 DataFrame 中的行数相等。

如何将这两列合并到一个新的 DataFrame 中?

我试过join,但我认为应该有其他方法可以做到这一点。

此外,我尝试应用 withColumm,但它无法编译。

val result = df1.withColumn(col("col2"), df2.col1)

更新:

例如:

df1 = 
col1
1
2
3

df2 =
col2
4
5
6

result =
col1 col2
1 4
2 5
3 6

最佳答案

如果这两列之间没有实际关系,听起来你需要联合运算符,它将返回,嗯,只是这两个数据帧的联合:

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 |
+---+

[编辑]现在您已经明确表示您只需要两列,然后使用 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 |
+---+---+

关于scala - 如何将两列合并到一个新的 DataFrame 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47479946/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com