scala - 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 连接)
解决方案
试试下面的代码
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|
+---+------+------+----+-----+
推荐阅读
- html - HTML CSS 不起作用
- azure-active-directory - Azure B2C 自定义策略外部数据源身份验证
- c - 如何检查输入是否是C中的整数?
- c++ - 如何在虚幻引擎 5 中将 Rotation 转换为 FVector?
- r - 带有管道的 if 语句
- r - 第n组标签(仅计算新组的毕业生)
- laravel-livewire - 在编辑模式下打开页面时如何填充状态/区域/子区域选择?
- palantir-foundry - 如何在保留已删除行的同时合并增量数据集和快照数据集?
- concurrency - 在一个简单的并发程序中证明不变量(大学示例问题)
- docker - 在 Windows Server 2019 上使用 Balena-cli 部署时出现 Docker 错误“不是目录”