根据 Spark 中的其他列值更新列中的值

时间:2021-03-04 14:42:20

标签: scala apache-spark user-defined-functions

我想根据行中任意数量的其他列的值设置 Spark DataFrame 中列的值。

我意识到我可以这样做:

a.Cs

但是对于具有 20 多列的数据框,必须有更好的方法来做到这一点。

该行包含偶数列,应成对检查,​​以了解“IsValid”列是 df.withColumn("IsValid", when($"col1" === $"col2" && $"col3" === $"col4", true).otherwise(false)) 还是 true

2 个答案:

答案 0 :(得分:1)

您可以尝试将列列表映射并减少到您想要的条件:

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))

答案 1 :(得分:1)

另一种将列成对分组并构造函数 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)) 
相关问题