【问题标题】:Chained Dataframe transformations in Scala with arguments and conditionsScala 中带有参数和条件的链式数据框转换
【发布时间】:2021-07-24 02:32:34
【问题描述】:

我在 Scala 中有一个数据框,我想根据作为参数传递给函数的条件为其添加转换和过滤器。

例如,我正在尝试做这样的事情:


val lst_conditions = List("condition1","condition2",..., "conditionN")

for (condition_string <- lst_conditions) {
var new_df = df.transform(FilterOrNot(condition_string))
}

但是我接下来如何定义函数不起作用:


def FilterOrNot(c: String) (df: DataFrame): DataFrame = {
  if (c == "condition1") df.filter($"price" >= $"avg_price")
  else if (c == "condition2") df.filter($"price" >= $"median_price")
// If the condition is different do nothing.
}

我得到的错误是:

<console>:73: error: type mismatch;
 found   : Unit
 required: org.apache.spark.sql.DataFrame
    (which expands to)  org.apache.spark.sql.Dataset[org.apache.spark.sql.Row]
         else if ...
              ^

我该如何实现?

【问题讨论】:

    标签: scala dataframe apache-spark-sql


    【解决方案1】:

    我认为关于下一个函数为什么不起作用或它没有做什么的更多信息可能会有用。

    我可能会建议添加的一件事是您的自定义转换的最终默认值,如下所示:

    def FilterOrNot(c: String) (df: DataFrame): DataFrame = {
      if (c == "condition1") df.filter($"price" >= $"avg_price")
      else if (c == "condition2") df.filter($"price" >= $"median_price")
      else df 
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-15
      • 1970-01-01
      • 2017-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多