根据 Spark 中的其他列值更新列中的值
Update value in column based on other column values in Spark
我想根据行中任意数量的其他列的值设置 Spark DataFrame 中列的值。
我意识到我可以这样做:
df.withColumn("IsValid", when($"col1" === $"col2" && $"col3" === $"col4", true).otherwise(false))
但是必须有更好的方法来处理 20 列以上的数据框。
该行包含偶数列,应成对检查这些列,以确定“IsValid”列是 true
还是 false
。
您可以尝试将列列表映射和缩减为您想要的条件:
val cond = (0 to df.columns.length - 1 by 2)
.map(i => (col(df.columns(i)) === col(df.columns(i+1))))
.reduce(_ && _)
df.withColumn("IsValid", when(cond, true).otherwise(false))
另一种将列成对分组并构造 when 函数条件的方法:
val condition = df.columns.grouped(2).map{ case Array(a, b) => col(a) === col(b)}.reduce(_ and _)
val df1 = df.withColumn("IsValid", when(condition,true).otherwise(false))
我想根据行中任意数量的其他列的值设置 Spark DataFrame 中列的值。
我意识到我可以这样做:
df.withColumn("IsValid", when($"col1" === $"col2" && $"col3" === $"col4", true).otherwise(false))
但是必须有更好的方法来处理 20 列以上的数据框。
该行包含偶数列,应成对检查这些列,以确定“IsValid”列是 true
还是 false
。
您可以尝试将列列表映射和缩减为您想要的条件:
val cond = (0 to df.columns.length - 1 by 2)
.map(i => (col(df.columns(i)) === col(df.columns(i+1))))
.reduce(_ && _)
df.withColumn("IsValid", when(cond, true).otherwise(false))
另一种将列成对分组并构造 when 函数条件的方法:
val condition = df.columns.grouped(2).map{ case Array(a, b) => col(a) === col(b)}.reduce(_ and _)
val df1 = df.withColumn("IsValid", when(condition,true).otherwise(false))