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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
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]))