【问题标题】:Update value in column based on other column values in Spark根据 Spark 中的其他列值更新列中的值
【发布时间】:2021-03-04 14:42:20
【问题描述】:

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

我意识到我可以这样做:

df.withColumn("IsValid", when($"col1" === $"col2" && $"col3" === $"col4", true).otherwise(false))

但是对于具有 20 列以上的数据帧,必须有更好的方法来执行此操作。

该行包含偶数列,应成对检查以了解“IsValid”列是true 还是false

【问题讨论】:

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


    【解决方案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))
    

    【讨论】:

      【解决方案2】:

      另一种成对分组列并为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)) 
      

      【讨论】:

        猜你喜欢
        • 2021-10-19
        • 2022-08-18
        • 1970-01-01
        • 1970-01-01
        • 2020-07-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-19
        相关资源
        最近更新 更多