小编Yas*_*ava的帖子

在Spark中循环更新列值

简要问题

对于更直接的查询,我想依次遍历所有行,并根据特定行的某些条件为某些变量(a,b,c)分配一些值,然后我将分配其中1个的值变量放入该特定行的一列中。

详细说明

我想在Spark中更新数据框中的列值。更新将是有条件的,其中我将在行上运行循环并根据该行其他列的值更新一列。

我尝试使用withColumn方法,但出现错误。请提出任何其他方法。withColumn方法的解析也将有很大帮助。

var table1 = Seq((11, 25, 2, 0), (42, 20, 10, 0)).toDF("col_1", "col_2", "col_3", "col_4")
table1.show()
Run Code Online (Sandbox Code Playgroud)

架构

+-----+-----+-----+-----+
|col_1|col_2|col_3|col_4|
+-----+-----+-----+-----+
|   11|   25|    2|    0|
|   42|   20|   10|    0|
+-----+-----+-----+-----+
Run Code Online (Sandbox Code Playgroud)

我在这里尝试了2种方法:

  1. withColumn
  2. i(“ col_4”)= adj_c

在下面的代码中,根据条件,仅需要以这种方式放置在不同位置初始化的变量

代码

for(i <- table1.rdd.collect()) {
    if(i.getAs[Int]("col_1") > 0) {
       var adj_a = 0
       var adj_c = 0
        if(i.getAs[Int]("col_1") > (i.getAs[Int]("col_2") + i.getAs[Int]("col_3"))) {
            if(i.getAs[Int]("col_1") < i.getAs[Int]("col_2")) {
                adj_a = 10
                adj_c = 2 …
Run Code Online (Sandbox Code Playgroud)

scala apache-spark

6
推荐指数
2
解决办法
552
查看次数

标签 统计

apache-spark ×1

scala ×1