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

标签 scala apache-spark dataframe

我有两个 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/

相关文章:

scala - 如何捕获异常并重定向到 Lift 中的错误页面?

java - 如何将不同的值传递给 scala 对象中的变量

apache-spark - Spark作业永远不会从ACCEPTED状态接受,并且挂起状态为UNDEFINED

scala - 在 Spark 2+ 中通过 SparkSession 向 Kryo 注册类

r - 过滤具有至少一个特定值的行

scala - 在 Scala 中的 Future[T] 中包装阻塞 Try[T] 的最佳方法是什么?

java - Apache Spark 简单连接导致神秘错误

r - 根据 R 中的名称从 data.frames 列表中删除 data.frame

python - Pandas Dataframe 具有各种列标准的求和函数

scala - 什么是 TrieMap,与 HashMap 相比,它的优点/缺点是什么?