【问题标题】:scala - how to add a new column to Dataframe depending on the values of another one? [duplicate]scala - 如何根据另一列的值向 Dataframe 添加新列? [复制]
【发布时间】:2019-01-08 20:02:14
【问题描述】:

我创建了一个包含销售信息的数据框。现在我想在数据帧中添加一个带有布尔值的列(metric1),其值将取决于sl.review 字段:如果sl.review 包含一个空字符串,那么metric1 将为false,true 否则如果sl.review 中有评论。

val salesDf: DataFrame = salesRawDf.select($"stores", explode($"sales").as("sl"))
      .select($"stores.id", $"stores.name", $"sl.id", $"sl.current_sales", $"sl.review")

如何使用 DataFrame 来实现?我已经阅读了这个相关的question,但仍然无法弄清楚如何在我的情况下实现它。

【问题讨论】:

    标签: scala apache-spark dataframe apache-spark-sql


    【解决方案1】:

    你可以像下面这样使用spark的when函数

    //Input df
    
    +---+--------+-------+
    |mid|   mname|mreview|
    +---+--------+-------+
    |100|     abc|       |
    |101|     bcd|   Good|
    |104|avengers|   Best|
    |108|    Heri|       |
    +---+--------+-------+
    
    //Solution
    
    import org.apache.spark.sql.functions._
    df.withColumn("metric1", when(df.col("mreview") === "", false) otherwise true).show
    
    //Output df
    
    +---+--------+-------+-------+
    |mid|   mname|mreview|metric1|
    +---+--------+-------+-------+
    |100|     abc|       |  false|
    |101|     bcd|   Good|   true|
    |104|avengers|   Best|   true|
    |108|    Heri|       |  false|
    +---+--------+-------+-------+
    

    希望对你有帮助

    【讨论】:

      【解决方案2】:

      尝试使用这个用户定义函数,它接受多个单个值作为参数:

      def reviewIsEmpty = udf((review: String) => {
        review.isEmpty
      })
      

      然后只需调用它创建新列:

      import spark.implicits._
      salesDf.withColumn("metric1", reviewIsEmpty($"sl.review"))
      

      当然,您可以更改 UDF 的行为以检查字符串是否不仅由空格组成,例如。

      希望对你有帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-09
        • 1970-01-01
        • 1970-01-01
        • 2018-09-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-15
        相关资源
        最近更新 更多