How to Implement IF-THEN-ELSE Logic in Spark Using `when()`?

Susan Sarandon
Release: 2024-11-18 07:09:02
Original
545 people have browsed it

How to Implement IF-THEN-ELSE Logic in Spark Using `when()`?

Spark Equivalent of IF Then ELSE

In this example, we aim to add a new column "Class" to the "iris_spark" DataFrame based on the values of an existing categorical column, "iris_class," which has three distinct categories.

The provided code, however, encounters an error:

iris_spark_df = iris_spark.withColumn(
    "Class", 
   F.when(iris_spark.iris_class == 'Iris-setosa', 0, F.when(iris_spark.iris_class == 'Iris-versicolor',1)).otherwise(2))
Copy after login

The error message indicates that the when() function in Spark takes only two arguments, contrary to the provided code.

To address this issue, the correct structure for using the when() function is either:

(when(col("iris_class") == 'Iris-setosa', 0)
.when(col("iris_class") == 'Iris-versicolor', 1)
.otherwise(2))
Copy after login

or

(when(col("iris_class") == 'Iris-setosa', 0)
    .otherwise(when(col("iris_class") == 'Iris-versicolor', 1)
        .otherwise(2)))
Copy after login

These expressions are equivalent to the SQL CASE statements:

CASE 
    WHEN (iris_class = 'Iris-setosa') THEN 0
    WHEN (iris_class = 'Iris-versicolor') THEN 1 
    ELSE 2
END
Copy after login

and

CASE WHEN (iris_class = 'Iris-setosa') THEN 0 
     ELSE CASE WHEN (iris_class = 'Iris-versicolor') THEN 1 
               ELSE 2 
          END 
END
Copy after login

respectively.

The general syntax of when() in Spark is:

when(condition, value).when(...)
Copy after login

or

when(condition, value).otherwise(...)
Copy after login

Note that the Hive IF conditional expression IF(condition, if-true, if-false) is not supported directly in Spark and can only be used in raw SQL with Hive support.

The above is the detailed content of How to Implement IF-THEN-ELSE Logic in Spark Using `when()`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template