Skip to main content

when

Evaluates a list of conditions and returns one of multiple possible result expressions. If otherwise() is not invoked, None is returned for unmatched conditions. Supports Spark Connect.

Syntax​

Python
from pyspark.sql import functions as dbf

dbf.when(condition=<condition>, value=<value>)

Parameters​

Parameter

Type

Description

condition

pyspark.sql.Column

A boolean Column expression.

value

Any

A literal value, or a Column expression.

Parameter

Type

Description

condition

pyspark.sql.Column

A boolean Column expression.

value

Any

A literal value, or a Column expression.

Returns​

pyspark.sql.Column: column representing when expression.

Examples​

Python
from pyspark.sql import functions as dbf
df = spark.range(3)
df.select("*", dbf.when(df['id'] == 2, 3).otherwise(4)).show()
Output
+---+------------------------------------+
| id|CASE WHEN (id = 2) THEN 3 ELSE 4 END|
+---+------------------------------------+
| 0| 4|
| 1| 4|
| 2| 3|
+---+------------------------------------+