---
title: try_cast
description: "Column.try\\_cast method in PySpark: Try to convert the column to a different data type. Returns null if conversion fails."
canonical_url: https://docs.databricks.com/aws/en/pyspark/reference/classes/column/try_cast
---

# 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` | 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|
# +-----+
```
