列由火花增加了另一列

时间:2019-06-20 09:46:04

标签: apache-spark apache-spark-mllib

数据源是:

   col1
------
    false
    false
    true
    false
    false
    true
    true
    false

我添加了一个新列,如果col1的值为true,则col2的值增加1。 我希望:

col1,col2
--

    false,0
    false,0
    true,1
    false,1
    false,1
    true,2
    true,3
    false,3

如何添加呢?

2 个答案:

答案 0 :(得分:0)

可以使用窗口功能:

val df = Seq(false, false, true, false, false, true, true, false).toDF("col1")
val ordered = df
  .withColumn("id", monotonically_increasing_id())
  .withColumn("increment", when($"col1" === true, 1).otherwise(0))

val idWindow = Window.orderBy("id").rowsBetween(Window.unboundedPreceding, Window.currentRow)
val result = ordered.select($"col1", sum($"increment").over(idWindow).alias("col2"))

输出:

+-----+----+
|col1 |col2|
+-----+----+
|false|0   |
|false|0   |
|true |1   |
|false|1   |
|false|1   |
|true |2   |
|true |3   |
|false|3   |
+-----+----+

答案 1 :(得分:0)

scala> import org.apache.spark.sql.expressions.Window
scala> val w = Window.partitionBy(lit(1)).orderBy(lit(1))
scala> val w1 = Window.partitionBy(lit(1)).orderBy("rn")

scala> df.withColumn("tmp", when($"col1" === true, 1).otherwise(0)).withColumn("rn", row_number.over(w)).withColumn("col2", sum("tmp").over(w1)).select("col1","col2").show
+-----+----+
| col1|col2|
+-----+----+
|false|   0|
|false|   0|
| true|   1|
|false|   1|
|false|   1|
| true|   2|
| true|   3|
|false|   3|
+-----+----+