scala - 如何使用列名随机更新特定行的列值
问题描述
def getSequence(row : Row) : Seq[String] = {
some code
}
基本上我想逐行迭代dataFrame,并用1更新我从getSequence获得的序列的值。
输入
+---+----+-----+
|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 |
+---+----+-----+
解决方案
def lit(literal: Any): org.apache.spark.sql.Column
def monotonically_increasing_id(): org.apache.spark.sql.Column
使用lit
函数更新列值。
请检查以下代码以更新特定列。
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 |
+---+----+-----+
推荐阅读
- java - 在同一方法中调用方法名称?
- python - 将列表拆分为 N 个子列表,总和大致相等
- html - 元素应该在换行符上时移动到 Div 的右侧
- python - 如何从列表中删除列表
- python - 无法为我的 pygame 创建多个敌人
- javascript - 如何以角度从字典对象中排除匹配值?
- java - 我怎样才能给玩家一个随机块?谢谢!(Minecraft Forge 改装 1.15)
- python - 在表达式中迭代序列的子序列(块)
- javascript - 两个不同的 Heroku 构建尝试构建相同的包,但一个出现错误。我很困惑
- azure-data-factory - 如何从同一列的多行计算变量或逗号分隔值列