snowflake.snowpark.functions.when¶
- snowflake.snowpark.functions.when(condition: Union[Column, str], value: Union[Column, None, bool, int, float, str, bytearray, Decimal, date, datetime, time, bytes, NaTType, float64, list, tuple, dict]) CaseExpr [source] (https://github.com/snowflakedb/snowpark-python/blob/v1.16.0/src/snowflake/snowpark/functions.py#L6503-L6542)¶
Works like a cascading if-then-else statement. A series of conditions are evaluated in sequence. When a condition evaluates to TRUE, the evaluation stops and the associated result (after THEN) is returned. If none of the conditions evaluate to TRUE, then the result after the optional OTHERWISE is returned, if present; otherwise NULL is returned.
- Parameters:
condition – A
Column
expression or SQL text representing the specified condition.value – A
Column
expression or a literal value, which will be returned ifcondition
is true.
Example:
>>> df = session.create_dataframe([1, None, 2, 3, None, 5, 6], schema=["a"]) >>> df.collect() [Row(A=1), Row(A=None), Row(A=2), Row(A=3), Row(A=None), Row(A=5), Row(A=6)] >>> df.select(when(col("a") % 2 == 0, lit("even")).as_("ans")).collect() [Row(ANS=None), Row(ANS=None), Row(ANS='even'), Row(ANS=None), Row(ANS=None), Row(ANS=None), Row(ANS='even')]
Multiple when statements can be changed and otherwise/else_ used to create expressions similar to
CASE WHEN ... ELSE ... END
in SQL.Example:
>>> df.select(when(col("a") % 2 == 0, lit("even")).when(col("a") % 2 == 1, lit("odd")).as_("ans")).collect() [Row(ANS='odd'), Row(ANS=None), Row(ANS='even'), Row(ANS='odd'), Row(ANS=None), Row(ANS='odd'), Row(ANS='even')] >>> df.select(when(col("a") % 2 == 0, lit("even")).when(col("a") % 2 == 1, lit("odd")).otherwise(lit("unknown")).as_("ans")).collect() [Row(ANS='odd'), Row(ANS='unknown'), Row(ANS='even'), Row(ANS='odd'), Row(ANS='unknown'), Row(ANS='odd'), Row(ANS='even')]