Skip to content

daft.functions.coalesce#

coalesce #

coalesce(*args: Expression) -> Expression

Returns the first non-null value in a list of expressions. If all inputs are null, returns null.

Parameters:

Name Type Description Default
*args Expression

Two or more expressions to coalesce

()

Returns:

Name Type Description
Expression Expression

Expression containing first non-null value encountered when evaluating arguments in order

Examples:

1
2
3
4
5
>>> import daft
>>> from daft.functions import coalesce
>>> df = daft.from_pydict({"x": [1, None, 3], "y": [None, 2, None]})
>>> df = df.with_column("first_valid", coalesce(df["x"], df["y"]))
>>> df.show()
╭───────┬───────┬─────────────╮
│ x     ┆ y     ┆ first_valid │
│ ---   ┆ ---   ┆ ---         │
│ Int64 ┆ Int64 ┆ Int64       │
╞═══════╪═══════╪═════════════╡
│ 1     ┆ None  ┆ 1           │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ None  ┆ 2     ┆ 2           │
├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 3     ┆ None  ┆ 3           │
╰───────┴───────┴─────────────╯
(Showing first 3 of 3 rows)
Source code in daft/functions/misc.py
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
def coalesce(*args: Expression) -> Expression:
    """Returns the first non-null value in a list of expressions. If all inputs are null, returns null.

    Args:
        *args: Two or more expressions to coalesce

    Returns:
        Expression: Expression containing first non-null value encountered when evaluating arguments in order

    Examples:
        >>> import daft
        >>> from daft.functions import coalesce
        >>> df = daft.from_pydict({"x": [1, None, 3], "y": [None, 2, None]})
        >>> df = df.with_column("first_valid", coalesce(df["x"], df["y"]))
        >>> df.show()
        ╭───────┬───────┬─────────────╮
        │ x     ┆ y     ┆ first_valid │
        │ ---   ┆ ---   ┆ ---         │
        │ Int64 ┆ Int64 ┆ Int64       │
        ╞═══════╪═══════╪═════════════╡
        │ 1     ┆ None  ┆ 1           │
        ├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
        │ None  ┆ 2     ┆ 2           │
        ├╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
        │ 3     ┆ None  ┆ 3           │
        ╰───────┴───────┴─────────────╯
        <BLANKLINE>
        (Showing first 3 of 3 rows)

    """
    return Expression._from_pyexpr(native.coalesce([arg._expr for arg in args]))

    if len(args) == 0:
        raise ValueError("coalesce requires at least one argument")
    if len(args) == 1:
        return args[0]
    return Expression._from_pyexpr(native.coalesce([arg._expr for arg in args]))