try_cast
Try to convert the column to a different data type. Returns null if conversion fails.
Added in Databricks Runtime 15.0
Syntax
Python
try_cast(dataType)
Parameters
Parameter | Type | Description |
|---|---|---|
| DataType or str | Target data type |
Returns
Column
Examples
Example 1: Cast with a DataType.
Python
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()
Output
# +----+
# |name|
# +----+
# | 123|
# |NULL|
# |NULL|
# +----+
Example 2: Cast with a DDL string.
Python
df = spark.createDataFrame(
[(2, "123"), (5, "Bob"), (3, None)], ["age", "name"])
df.select(df.name.try_cast("double")).show()
Output
# +-----+
# | name|
# +-----+
# |123.0|
# | NULL|
# | NULL|
# +-----+