Skip to main content

assert_true

Returns null if the input column is true; throws an exception with the provided error message otherwise.

Syntax​

Python
from pyspark.sql import functions as sf

sf.assert_true(col, errMsg=None)

Parameters​

Parameter

Type

Description

col

pyspark.sql.Column or str

Column name or column that represents the input column to test.

errMsg

pyspark.sql.Column or str, optional

A Python string literal or column containing the error message.

Parameter

Type

Description

col

pyspark.sql.Column or str

Column name or column that represents the input column to test.

errMsg

pyspark.sql.Column or str, optional

A Python string literal or column containing the error message.

Returns​

pyspark.sql.Column: null if the input column is true otherwise throws an error with specified message.

Examples​

Example 1: Assert a true condition

Python
from pyspark.sql import functions as sf
df = spark.createDataFrame([(0, 1)], ['a', 'b'])
df.select('*', sf.assert_true(df.a < df.b)).show()
Output
+---+---+--------------------------------------------+
| a| b|assert_true((a < b), '(a < b)' is not true!)|
+---+---+--------------------------------------------+
| 0| 1| NULL|
+---+---+--------------------------------------------+

Example 2: Assert with column error message

Python
from pyspark.sql import functions as sf
df = spark.createDataFrame([(0, 1)], ['a', 'b'])
df.select('*', sf.assert_true(df.a < df.b, df.a)).show()
Output
+---+---+-----------------------+
| a| b|assert_true((a < b), a)|
+---+---+-----------------------+
| 0| 1| NULL|
+---+---+-----------------------+

Example 3: Assert with custom error message

Python
from pyspark.sql import functions as sf
df = spark.createDataFrame([(0, 1)], ['a', 'b'])
df.select('*', sf.assert_true(df.a < df.b, 'error')).show()
Output
+---+---+---------------------------+
| a| b|assert_true((a < b), error)|
+---+---+---------------------------+
| 0| 1| NULL|
+---+---+---------------------------+