Как обновить значение столбца для определенной строки случайным образом, используя имя столбца - PullRequest
0 голосов
/ 06 мая 2020
def getSequence(row : Row) : Seq[String] = {
some code
}

В основном я хочу перебирать dataFrame за строкой и обновлять значение с 1 для последовательности, которую я получаю из getSequence.

Input

+---+----+-----+
|sno|dept|color|
+---+----+-----+
|  1|  0 |  0  |
|  2|  0 |  0  |
|  3|  0 |  0  |
+---+----+-----+

getSequence for Row 1 give Seq("dept")
Row 2 give Seq("color") Row 3 give Seq("dept","color")
output be like 
+---+----+-----+
|sno|dept|color|
+---+----+-----+
|  1|  1 |  0  |
|  2|  0 |  1  |
|  3|  1 |  1  |
+---+----+-----+

1 Ответ

0 голосов
/ 06 мая 2020

def lit(literal: Any): org.apache.spark.sql.Column

def monotonically_increasing_id(): org.apache.spark.sql.Column

Используйте функцию lit для обновления значений столбцов.

Пожалуйста, проверьте приведенный ниже код для обновления столбца c.

scala> val df = Seq((1,0,0),(2,0,0),(3,0,0)).toDF("sno","dept","color").withColumn("id",monotonically_increasing_id)
df: org.apache.spark.sql.DataFrame = [sno: int, dept: int ... 2 more fields]

scala> df.withColumn("dept",when($"id" =!= 1,lit(1)).otherwise(lit(0))).withColumn("color",when($"id" =!= 0,lit(1)).otherwise(lit(0))).drop("id").show(false)
+---+----+-----+
|sno|dept|color|
+---+----+-----+
|1  |1   |0    |
|2  |0   |1    |
|3  |1   |1    |
+---+----+-----+

...