使用一个when子句添加多列

时间:2019-10-29 08:58:16

标签: scala apache-spark

我有一个看起来像这样的代码:

{this.state.results}

不必理解该代码,但我的目标是只能使用一个when子句并一次添加2列。
进行两次此测试以添加列是一个可怕的性能问题,可能吗?
我尝试使用df.withColumn( colPath , when( col(colType) =!= S_IFLNK_name, regexp_extract(col(tempColPath) , exp = "^(.*\\/).*$", groupIdx = 1 ) ) .otherwise( regexp_extract( col(tempColPath), exp = "^(.*\\/)(?:[^\\/]+\\-\\>.*)$", groupIdx = 1 ) ) ) .withColumn( colFilename, when( col(colType) =!= S_IFLNK_name, regexp_extract(col(tempColPath), exp = "^(?:.*\\/)(.*)$", groupIdx = 1 ) ) .otherwise( regexp_extract( col(tempColPath), exp = "^(?:.*\\/)([^\\/]+\\-\\>.*)$", groupIdx = 1 ) ) ) ,但是您不能将它们应用于match case值。

1 个答案:

答案 0 :(得分:0)

摘自withColumn:(https://spark.apache.org/docs/2.4.4/api/java/org/apache/spark/sql/Dataset.html#withColumn-java.lang.String-org.apache.spark.sql.Column-)的spark文档:

  

通过添加一列或替换具有相同名称的现有列来返回新的数据集。

因此,对于您需要添加的每个新列,请使用.withColumn

yourDF
  .withColumn("new_column",
    when($"old_column".isNull, lit("new_column_true_value"))
      .otherwise($"new_column_false_value"))
  .withColumn("new_column_2",
    when($"old_column_2".isNull, lit("new_column_2_true_value"))
      .otherwise($"new_column_2_false_value"))