Skip to content

Aggregations#

When performing aggregations such as sum, mean and count, Daft enables you to group data by certain keys and aggregate within those keys.

Calling df.groupby() returns a GroupedDataFrame object which is a view of the original DataFrame but with additional context on which keys to group on. You can then call various aggregation methods to run the aggregation within each group, returning a new DataFrame.

GroupedDataFrame #

GroupedDataFrame(df: DataFrame, group_by: ExpressionsProjection)

Methods:

Name Description
agg

Perform aggregations on this GroupedDataFrame. Allows for mixed aggregations.

any_value

Returns an arbitrary value on this GroupedDataFrame.

count

Performs grouped count on this GroupedDataFrame.

count_distinct

Performs grouped count of distinct values on this GroupedDataFrame.

list_agg

Performs grouped list on this GroupedDataFrame.

list_agg_distinct

Performs grouped list distinct on this GroupedDataFrame (ignoring nulls).

map_groups

Apply a user-defined function to each group. The name of the resultant column will default to the name of the first input column.

max

Performs grouped max on this GroupedDataFrame.

mean

Performs grouped mean on this GroupedDataFrame.

min

Perform grouped min on this GroupedDataFrame.

product

Performs grouped product on this GroupedDataFrame.

skew

Performs grouped skew on this GroupedDataFrame.

stddev

Performs grouped standard deviation on this GroupedDataFrame.

string_agg

Performs grouped string concat on this GroupedDataFrame.

sum

Perform grouped sum on this GroupedDataFrame.

var

Performs grouped variance on this GroupedDataFrame.

Attributes:

Name Type Description
df DataFrame
group_by ExpressionsProjection

df #

group_by #

group_by: ExpressionsProjection

agg #

agg(*to_agg: Expression | Iterable[Expression]) -> DataFrame

Perform aggregations on this GroupedDataFrame. Allows for mixed aggregations.

Parameters:

Name Type Description Default
*to_agg Union[Expression, Iterable[Expression]]

aggregation expressions

()

Returns:

Name Type Description
DataFrame DataFrame

DataFrame with grouped aggregations

Examples:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
>>> import daft
>>> from daft import col
>>> df = daft.from_pydict(
...     {
...         "pet": ["cat", "dog", "dog", "cat"],
...         "age": [1, 2, 3, 4],
...         "name": ["Alex", "Jordan", "Sam", "Riley"],
...     }
... )
>>> grouped_df = df.groupby("pet").agg(
...     df["age"].min().alias("min_age"),
...     df["age"].max().alias("max_age"),
...     df["pet"].count().alias("count"),
...     df["name"].any_value(),
... )
>>> grouped_df = grouped_df.sort("pet")
>>> grouped_df.show()
╭────────┬─────────┬─────────┬────────┬────────╮
│ pet    ┆ min_age ┆ max_age ┆ count  ┆ name   │
│ ---    ┆ ---     ┆ ---     ┆ ---    ┆ ---    │
│ String ┆ Int64   ┆ Int64   ┆ UInt64 ┆ String │
╞════════╪═════════╪═════════╪════════╪════════╡
│ cat    ┆ 1       ┆ 4       ┆ 2      ┆ Alex   │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
│ dog    ┆ 2       ┆ 3       ┆ 2      ┆ Jordan │
╰────────┴─────────┴─────────┴────────┴────────╯
(Showing first 2 of 2 rows)
Source code in daft/dataframe/dataframe.py
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
def agg(self, *to_agg: Expression | Iterable[Expression]) -> DataFrame:
    """Perform aggregations on this GroupedDataFrame. Allows for mixed aggregations.

    Args:
        *to_agg (Union[Expression, Iterable[Expression]]): aggregation expressions

    Returns:
        DataFrame: DataFrame with grouped aggregations

    Examples:
        >>> import daft
        >>> from daft import col
        >>> df = daft.from_pydict(
        ...     {
        ...         "pet": ["cat", "dog", "dog", "cat"],
        ...         "age": [1, 2, 3, 4],
        ...         "name": ["Alex", "Jordan", "Sam", "Riley"],
        ...     }
        ... )
        >>> grouped_df = df.groupby("pet").agg(
        ...     df["age"].min().alias("min_age"),
        ...     df["age"].max().alias("max_age"),
        ...     df["pet"].count().alias("count"),
        ...     df["name"].any_value(),
        ... )
        >>> grouped_df = grouped_df.sort("pet")
        >>> grouped_df.show()
        ╭────────┬─────────┬─────────┬────────┬────────╮
        │ pet    ┆ min_age ┆ max_age ┆ count  ┆ name   │
        │ ---    ┆ ---     ┆ ---     ┆ ---    ┆ ---    │
        │ String ┆ Int64   ┆ Int64   ┆ UInt64 ┆ String │
        ╞════════╪═════════╪═════════╪════════╪════════╡
        │ cat    ┆ 1       ┆ 4       ┆ 2      ┆ Alex   │
        ├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
        │ dog    ┆ 2       ┆ 3       ┆ 2      ┆ Jordan │
        ╰────────┴─────────┴─────────┴────────┴────────╯
        <BLANKLINE>
        (Showing first 2 of 2 rows)

    """
    to_agg_list = (
        list(to_agg[0])
        if (len(to_agg) == 1 and not isinstance(to_agg[0], Expression))
        else list(typing.cast("tuple[Expression]", to_agg))
    )

    for expr in to_agg_list:
        if not isinstance(expr, Expression):
            raise ValueError(f"GroupedDataFrame.agg() only accepts expression type, received: {type(expr)}")

    return self.df._agg(to_agg_list, group_by=self.group_by)

any_value #

any_value(*cols: ColumnInputType) -> DataFrame

Returns an arbitrary value on this GroupedDataFrame.

Values for each column are not guaranteed to be from the same row.

Parameters:

Name Type Description Default
*cols Union[str, Expression]

columns to get

()

Returns:

Name Type Description
DataFrame DataFrame

DataFrame with any values.

Source code in daft/dataframe/dataframe.py
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
def any_value(self, *cols: ColumnInputType) -> DataFrame:
    """Returns an arbitrary value on this GroupedDataFrame.

    Values for each column are not guaranteed to be from the same row.

    Args:
        *cols (Union[str, Expression]): columns to get

    Returns:
        DataFrame: DataFrame with any values.
    """
    return self.df._apply_agg_fn(Expression.any_value, cols, self.group_by)

count #

count(*cols: ColumnInputType) -> DataFrame

Performs grouped count on this GroupedDataFrame.

Returns:

Name Type Description
DataFrame DataFrame

DataFrame with grouped count per column.

Source code in daft/dataframe/dataframe.py
6392
6393
6394
6395
6396
6397
6398
def count(self, *cols: ColumnInputType) -> DataFrame:
    """Performs grouped count on this GroupedDataFrame.

    Returns:
        DataFrame: DataFrame with grouped count per column.
    """
    return self.df._apply_agg_fn(Expression.count, cols, self.group_by)

count_distinct #

count_distinct(*cols: ColumnInputType) -> DataFrame

Performs grouped count of distinct values on this GroupedDataFrame.

Parameters:

Name Type Description Default
*cols Union[str, Expression]

columns to count distinct values

()

Returns:

Name Type Description
DataFrame DataFrame

DataFrame with grouped count of distinct values per column.

Examples:

1
2
3
4
5
>>> import daft
>>> df = daft.from_pydict({"keys": ["a", "a", "a", "b", "b", "b"], "vals": [1, 1, 2, 3, 3, 3]})
>>> df = df.groupby("keys").count_distinct("vals")
>>> df = df.sort("keys")
>>> df.show()
╭────────┬────────╮
│ keys   ┆ vals   │
│ ---    ┆ ---    │
│ String ┆ UInt64 │
╞════════╪════════╡
│ a      ┆ 2      │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
│ b      ┆ 1      │
╰────────┴────────╯
(Showing first 2 of 2 rows)
Source code in daft/dataframe/dataframe.py
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
def count_distinct(self, *cols: ColumnInputType) -> DataFrame:
    """Performs grouped count of distinct values on this GroupedDataFrame.

    Args:
        *cols (Union[str, Expression]): columns to count distinct values

    Returns:
        DataFrame: DataFrame with grouped count of distinct values per column.

    Examples:
        >>> import daft
        >>> df = daft.from_pydict({"keys": ["a", "a", "a", "b", "b", "b"], "vals": [1, 1, 2, 3, 3, 3]})
        >>> df = df.groupby("keys").count_distinct("vals")
        >>> df = df.sort("keys")
        >>> df.show()
        ╭────────┬────────╮
        │ keys   ┆ vals   │
        │ ---    ┆ ---    │
        │ String ┆ UInt64 │
        ╞════════╪════════╡
        │ a      ┆ 2      │
        ├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
        │ b      ┆ 1      │
        ╰────────┴────────╯
        <BLANKLINE>
        (Showing first 2 of 2 rows)

    """
    return self.df._apply_agg_fn(Expression.count_distinct, cols, self.group_by)

list_agg #

list_agg(*cols: ColumnInputType) -> DataFrame

Performs grouped list on this GroupedDataFrame.

Returns:

Name Type Description
DataFrame DataFrame

DataFrame with grouped list per column.

Source code in daft/dataframe/dataframe.py
6468
6469
6470
6471
6472
6473
6474
def list_agg(self, *cols: ColumnInputType) -> DataFrame:
    """Performs grouped list on this GroupedDataFrame.

    Returns:
        DataFrame: DataFrame with grouped list per column.
    """
    return self.df._apply_agg_fn(Expression.list_agg, cols, self.group_by)

list_agg_distinct #

list_agg_distinct(*cols: ColumnInputType) -> DataFrame

Performs grouped list distinct on this GroupedDataFrame (ignoring nulls).

Parameters:

Name Type Description Default
*cols Union[str, Expression]

columns to form into a set

()

Returns:

Name Type Description
DataFrame DataFrame

DataFrame with grouped list distinct per column.

Source code in daft/dataframe/dataframe.py
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
def list_agg_distinct(self, *cols: ColumnInputType) -> DataFrame:
    """Performs grouped list distinct on this GroupedDataFrame (ignoring nulls).

    Args:
        *cols (Union[str, Expression]): columns to form into a set

    Returns:
        DataFrame: DataFrame with grouped list distinct per column.
    """
    return self.df._apply_agg_fn(Expression.list_agg_distinct, cols, self.group_by)

map_groups #

map_groups(udf: Expression) -> DataFrame

Apply a user-defined function to each group. The name of the resultant column will default to the name of the first input column.

Parameters:

Name Type Description Default
udf Expression

User-defined function to apply to each group.

required

Returns:

Name Type Description
DataFrame DataFrame

DataFrame with grouped aggregations

Examples:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
>>> import daft, statistics
>>>
>>> df = daft.from_pydict({"group": ["a", "a", "a", "b", "b", "b"], "data": [1, 20, 30, 4, 50, 600]})
>>>
>>> @daft.func.batch(return_dtype=daft.DataType.float64())
... def std_dev(data):
...     return [statistics.stdev(data)]
>>>
>>> df = df.groupby("group").map_groups(std_dev(df["data"]))
>>> df = df.sort("group")
>>> df.show()
╭────────┬────────────────────╮
│ group  ┆ data               │
│ ---    ┆ ---                │
│ String ┆ Float64            │
╞════════╪════════════════════╡
│ a      ┆ 14.730919862656235 │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ b      ┆ 331.62026476076517 │
╰────────┴────────────────────╯
(Showing first 2 of 2 rows)
Source code in daft/dataframe/dataframe.py
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
def map_groups(self, udf: Expression) -> DataFrame:
    """Apply a user-defined function to each group. The name of the resultant column will default to the name of the first input column.

    Args:
        udf (Expression): User-defined function to apply to each group.

    Returns:
        DataFrame: DataFrame with grouped aggregations

    Examples:
        >>> import daft, statistics
        >>>
        >>> df = daft.from_pydict({"group": ["a", "a", "a", "b", "b", "b"], "data": [1, 20, 30, 4, 50, 600]})
        >>>
        >>> @daft.func.batch(return_dtype=daft.DataType.float64())
        ... def std_dev(data):
        ...     return [statistics.stdev(data)]
        >>>
        >>> df = df.groupby("group").map_groups(std_dev(df["data"]))
        >>> df = df.sort("group")
        >>> df.show()
        ╭────────┬────────────────────╮
        │ group  ┆ data               │
        │ ---    ┆ ---                │
        │ String ┆ Float64            │
        ╞════════╪════════════════════╡
        │ a      ┆ 14.730919862656235 │
        ├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
        │ b      ┆ 331.62026476076517 │
        ╰────────┴────────────────────╯
        <BLANKLINE>
        (Showing first 2 of 2 rows)

    """
    return self.df._map_groups(udf, group_by=self.group_by)

max #

max(*cols: ColumnInputType) -> DataFrame

Performs grouped max on this GroupedDataFrame.

Parameters:

Name Type Description Default
*cols Union[str, Expression]

columns to max

()

Returns:

Name Type Description
DataFrame DataFrame

DataFrame with grouped max.

Source code in daft/dataframe/dataframe.py
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
def max(self, *cols: ColumnInputType) -> DataFrame:
    """Performs grouped max on this GroupedDataFrame.

    Args:
        *cols (Union[str, Expression]): columns to max

    Returns:
        DataFrame: DataFrame with grouped max.
    """
    return self.df._apply_agg_fn(Expression.max, cols, self.group_by)

mean #

mean(*cols: ColumnInputType) -> DataFrame

Performs grouped mean on this GroupedDataFrame.

Parameters:

Name Type Description Default
*cols Union[str, Expression]

columns to mean

()

Returns:

Name Type Description
DataFrame DataFrame

DataFrame with grouped mean.

Source code in daft/dataframe/dataframe.py
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
def mean(self, *cols: ColumnInputType) -> DataFrame:
    """Performs grouped mean on this GroupedDataFrame.

    Args:
        *cols (Union[str, Expression]): columns to mean

    Returns:
        DataFrame: DataFrame with grouped mean.
    """
    return self.df._apply_agg_fn(Expression.mean, cols, self.group_by)

min #

min(*cols: ColumnInputType) -> DataFrame

Perform grouped min on this GroupedDataFrame.

Parameters:

Name Type Description Default
*cols Union[str, Expression]

columns to min

()

Returns:

Name Type Description
DataFrame DataFrame

DataFrame with grouped min.

Source code in daft/dataframe/dataframe.py
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
def min(self, *cols: ColumnInputType) -> DataFrame:
    """Perform grouped min on this GroupedDataFrame.

    Args:
        *cols (Union[str, Expression]): columns to min

    Returns:
        DataFrame: DataFrame with grouped min.
    """
    return self.df._apply_agg_fn(Expression.min, cols, self.group_by)

product #

product(*cols: ColumnInputType) -> DataFrame

Performs grouped product on this GroupedDataFrame.

Parameters:

Name Type Description Default
*cols Union[str, Expression]

columns to product

()

Returns:

Name Type Description
DataFrame DataFrame

DataFrame with grouped products.

Examples:

1
2
3
4
5
>>> import daft
>>> df = daft.from_pydict({"keys": ["a", "a", "a", "b"], "col_a": [1, 2, 3, 100]})
>>> df = df.groupby("keys").product()
>>> df = df.sort("keys")
>>> df.show()
╭────────┬───────╮
│ keys   ┆ col_a │
│ ---    ┆ ---   │
│ String ┆ Int64 │
╞════════╪═══════╡
│ a      ┆ 6     │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ b      ┆ 100   │
╰────────┴───────╯
(Showing first 2 of 2 rows)
Source code in daft/dataframe/dataframe.py
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
def product(self, *cols: ColumnInputType) -> DataFrame:
    """Performs grouped product on this GroupedDataFrame.

    Args:
        *cols (Union[str, Expression]): columns to product

    Returns:
        DataFrame: DataFrame with grouped products.

    Examples:
        >>> import daft
        >>> df = daft.from_pydict({"keys": ["a", "a", "a", "b"], "col_a": [1, 2, 3, 100]})
        >>> df = df.groupby("keys").product()
        >>> df = df.sort("keys")
        >>> df.show()
        ╭────────┬───────╮
        │ keys   ┆ col_a │
        │ ---    ┆ ---   │
        │ String ┆ Int64 │
        ╞════════╪═══════╡
        │ a      ┆ 6     │
        ├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
        │ b      ┆ 100   │
        ╰────────┴───────╯
        <BLANKLINE>
        (Showing first 2 of 2 rows)

    """
    return self.df._apply_agg_fn(Expression.product, cols, self.group_by)

skew #

skew(*cols: ColumnInputType) -> DataFrame

Performs grouped skew on this GroupedDataFrame.

Returns:

Name Type Description
DataFrame DataFrame

DataFrame with the grouped skew per column.

Source code in daft/dataframe/dataframe.py
6400
6401
6402
6403
6404
6405
6406
def skew(self, *cols: ColumnInputType) -> DataFrame:
    """Performs grouped skew on this GroupedDataFrame.

    Returns:
        DataFrame: DataFrame with the grouped skew per column.
    """
    return self.df._apply_agg_fn(Expression.skew, cols, self.group_by)

stddev #

stddev(*cols: ColumnInputType, ddof: int = 1) -> DataFrame

Performs grouped standard deviation on this GroupedDataFrame.

Parameters:

Name Type Description Default
*cols Union[str, Expression]

columns to stddev

()
ddof int

Delta degrees of freedom used in the denominator N - ddof. Defaults to 1 (sample standard deviation).

1

Returns:

Name Type Description
DataFrame DataFrame

DataFrame with grouped standard deviation.

Examples:

1
2
3
4
5
>>> import daft
>>> df = daft.from_pydict({"keys": ["a", "a", "a", "b"], "col_a": [0, 1, 2, 100]})
>>> df = df.groupby("keys").stddev()
>>> df = df.sort("keys")
>>> df.show()
╭────────┬─────────╮
│ keys   ┆ col_a   │
│ ---    ┆ ---     │
│ String ┆ Float64 │
╞════════╪═════════╡
│ a      ┆ 1       │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┤
│ b      ┆ None    │
╰────────┴─────────╯
(Showing first 2 of 2 rows)
Source code in daft/dataframe/dataframe.py
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
def stddev(self, *cols: ColumnInputType, ddof: int = 1) -> DataFrame:
    """Performs grouped standard deviation on this GroupedDataFrame.

    Args:
        *cols (Union[str, Expression]): columns to stddev
        ddof (int): Delta degrees of freedom used in the denominator `N - ddof`.
            Defaults to 1 (sample standard deviation).

    Returns:
        DataFrame: DataFrame with grouped standard deviation.

    Examples:
        >>> import daft
        >>> df = daft.from_pydict({"keys": ["a", "a", "a", "b"], "col_a": [0, 1, 2, 100]})
        >>> df = df.groupby("keys").stddev()
        >>> df = df.sort("keys")
        >>> df.show()
        ╭────────┬─────────╮
        │ keys   ┆ col_a   │
        │ ---    ┆ ---     │
        │ String ┆ Float64 │
        ╞════════╪═════════╡
        │ a      ┆ 1       │
        ├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┤
        │ b      ┆ None    │
        ╰────────┴─────────╯
        <BLANKLINE>
        (Showing first 2 of 2 rows)

    """
    return self.df._apply_agg_fn(lambda expr: Expression.stddev(expr, ddof), cols, self.group_by)

string_agg #

string_agg(*cols: ColumnInputType, delimiter: str | None = None) -> DataFrame

Performs grouped string concat on this GroupedDataFrame.

Returns:

Name Type Description
DataFrame DataFrame

DataFrame with grouped string concatenated per column.

Source code in daft/dataframe/dataframe.py
6487
6488
6489
6490
6491
6492
6493
def string_agg(self, *cols: ColumnInputType, delimiter: str | None = None) -> DataFrame:
    """Performs grouped string concat on this GroupedDataFrame.

    Returns:
        DataFrame: DataFrame with grouped string concatenated per column.
    """
    return self.df._apply_agg_fn(lambda expr: Expression.string_agg(expr, delimiter=delimiter), cols, self.group_by)

sum #

sum(*cols: ColumnInputType) -> DataFrame

Perform grouped sum on this GroupedDataFrame.

Parameters:

Name Type Description Default
*cols Union[str, Expression]

columns to sum

()

Returns:

Name Type Description
DataFrame DataFrame

DataFrame with grouped sums.

Source code in daft/dataframe/dataframe.py
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
def sum(self, *cols: ColumnInputType) -> DataFrame:
    """Perform grouped sum on this GroupedDataFrame.

    Args:
        *cols (Union[str, Expression]): columns to sum

    Returns:
        DataFrame: DataFrame with grouped sums.
    """
    return self.df._apply_agg_fn(Expression.sum, cols, self.group_by)

var #

var(*cols: ColumnInputType, ddof: int = 1) -> DataFrame

Performs grouped variance on this GroupedDataFrame.

Parameters:

Name Type Description Default
*cols Union[str, Expression]

columns to compute variance for

()
ddof int

Delta degrees of freedom used in the denominator N - ddof. Defaults to 1 (sample variance).

1

Returns:

Name Type Description
DataFrame DataFrame

DataFrame with grouped variance.

Examples:

1
2
3
4
5
>>> import daft
>>> df = daft.from_pydict({"keys": ["a", "a", "a", "b"], "col_a": [0, 1, 2, 100]})
>>> df = df.groupby("keys").var()
>>> df = df.sort("keys")
>>> df.show()
╭────────┬─────────╮
│ keys   ┆ col_a   │
│ ---    ┆ ---     │
│ String ┆ Float64 │
╞════════╪═════════╡
│ a      ┆ 1       │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┤
│ b      ┆ None    │
╰────────┴─────────╯
(Showing first 2 of 2 rows)
Source code in daft/dataframe/dataframe.py
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
def var(self, *cols: ColumnInputType, ddof: int = 1) -> DataFrame:
    """Performs grouped variance on this GroupedDataFrame.

    Args:
        *cols (Union[str, Expression]): columns to compute variance for
        ddof (int): Delta degrees of freedom used in the denominator `N - ddof`.
            Defaults to 1 (sample variance).

    Returns:
        DataFrame: DataFrame with grouped variance.

    Examples:
        >>> import daft
        >>> df = daft.from_pydict({"keys": ["a", "a", "a", "b"], "col_a": [0, 1, 2, 100]})
        >>> df = df.groupby("keys").var()
        >>> df = df.sort("keys")
        >>> df.show()
        ╭────────┬─────────╮
        │ keys   ┆ col_a   │
        │ ---    ┆ ---     │
        │ String ┆ Float64 │
        ╞════════╪═════════╡
        │ a      ┆ 1       │
        ├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┤
        │ b      ┆ None    │
        ╰────────┴─────────╯
        <BLANKLINE>
        (Showing first 2 of 2 rows)

    """
    return self.df._apply_agg_fn(lambda expr: Expression.var(expr, ddof), cols, self.group_by)