Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Try to convert the column to a different data type. Returns null if conversion fails.
Added in Databricks Runtime 15.0
Syntax
try_cast(dataType)
Parameters
| Parameter | Type | Description |
|---|---|---|
dataType |
DataType or str | Target data type |
Returns
Column
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|
# +-----+