首页 > 解决方案 > Spark Scala 对两个数据框中的列进行一些数学运算

问题描述

我们有两个数据框:

+----+--------+--------+
| id | height | weight |
+----+--------+--------+
|  1 |    12  |      5 |
|  2 |      8 |      7 |
+----+--------+--------+

和另一个 :

+----+------+--------+
| id | Area | Area_2 |
+----+------+--------+
|  1 |      |        |
|  2 |      |        |
+----+------+--------+

我需要通过 id 连接两个数据帧,并且在第二个 df 中的结果必须是这样的:

+----+---------+--------+
| id |  Area   | Area_2 |
+----+---------+--------+
|  1 | (12*5)  | (12+5) |
|  2 | (8*7)   | (8+7)  |
+----+---------+--------+

(其中 Area 和 Area_2 需要从另一个 DF 得到 height 和 weight 之间的运算结果,并由 id 连接)

标签: scaladataframeapache-spark

解决方案


试试下面的代码

  val df1 = Seq((1, 12, 5), (2,8,7)).toDF("id", "height", "weight")
  val df2 = Seq((1),(2)).toDF("id") // drop area and area2 columns from this df
  val df3 = df1.withColumn("area", col("height")* col("weight")).withColumn("area2", col("height") + col("weight"))
  val finaldf = df2.join(df3, Seq("id"))

  scala> finaldf.show
  +---+------+------+----+-----+
  | id|height|weight|area|area2|
  +---+------+------+----+-----+
  |  1|    12|     5|  60|   17|
  |  2|     8|     7|  56|   15|
  +---+------+------+----+-----+

推荐阅读