pyspark.sql.Column.try_cast#

Column.try_cast(dataType)[source]#

This is a special version of cast that performs the same operation, but returns a NULL value instead of raising an error if the invoke method throws exception.

New in version 4.0.0.

Parameters
dataTypeDataType or str

a DataType or Python string literal with a DDL-formatted string to use when parsing the column to the same type.

Returns
Column

Column representing whether each element of Column is cast into new type.

Examples

Example 1: Cast with a Datatype

>>> from pyspark.sql.types import LongType
>>> df = spark.createDataFrame(
...      [(2, "123"), (5, "Bob"), (3, None)], ["age", "name"])
>>> df.select(df.name.try_cast(LongType())).show()
+----+
|name|
+----+
| 123|
|NULL|
|NULL|
+----+

Example 2: Cast with a DDL string

>>> df = spark.createDataFrame(
...      [(2, "123"), (5, "Bob"), (3, None)], ["age", "name"])
>>> df.select(df.name.try_cast("double")).show()
+-----+
| name|
+-----+
|123.0|
| NULL|
| NULL|
+-----+