Skip to content

daft.functions.try_cast#

try_cast #

try_cast(expr: Expression, dtype: DataTypeLike) -> Expression

Attempts to cast an expression to the given datatype, returning null on failure.

Unlike cast, this function does not raise an error when the conversion fails. Instead, it returns null for values that cannot be converted.

Returns:

Name Type Description
Expression Expression

Expression with the specified new datatype, with null for failed conversions

Note
  • If a string is provided, it will use the sql engine to parse the string into a data type.
  • A python type can also be provided, in which case the corresponding Daft data type will be used.

Examples:

1
2
3
4
>>> import daft
>>> df = daft.from_pydict({"str_val": ["1", "2", "abc", None]})
>>> df = df.select(df["str_val"].try_cast(daft.DataType.int64()))
>>> df.show()
╭─────────╮
│ str_val │
│ ---     │
│ Int64   │
╞═════════╡
│ 1       │
├╌╌╌╌╌╌╌╌╌┤
│ 2       │
├╌╌╌╌╌╌╌╌╌┤
│ None    │
├╌╌╌╌╌╌╌╌╌┤
│ None    │
╰─────────╯
(Showing first 4 of 4 rows)
Source code in daft/functions/misc.py
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
def try_cast(expr: Expression, dtype: DataTypeLike) -> Expression:
    """Attempts to cast an expression to the given datatype, returning null on failure.

    Unlike `cast`, this function does not raise an error when the conversion fails.
    Instead, it returns null for values that cannot be converted.

    Returns:
        Expression: Expression with the specified new datatype, with null for failed conversions

    Note:
        - If a string is provided, it will use the sql engine to parse the string into a data type.
        - A python `type` can also be provided, in which case the corresponding Daft data type will be used.

    Examples:
        >>> import daft
        >>> df = daft.from_pydict({"str_val": ["1", "2", "abc", None]})
        >>> df = df.select(df["str_val"].try_cast(daft.DataType.int64()))
        >>> df.show()
        ╭─────────╮
        │ str_val │
        │ ---     │
        │ Int64   │
        ╞═════════╡
        │ 1       │
        ├╌╌╌╌╌╌╌╌╌┤
        │ 2       │
        ├╌╌╌╌╌╌╌╌╌┤
        │ None    │
        ├╌╌╌╌╌╌╌╌╌┤
        │ None    │
        ╰─────────╯
        <BLANKLINE>
        (Showing first 4 of 4 rows)
    """
    dtype = DataType._infer(dtype)
    expr = Expression._to_expression(expr)
    return Expression._from_pyexpr(expr._expr.try_cast(dtype._dtype))