CertSafari
    Databricks Certified Associate Developer for Apache Spark· Lessons

    Domain 3 · Lesson 14/32

    DataFrame aggregations: count, mean, approx_count_distinct and summary

    Perform aggregate operations on DataFrames such as count, approximate count distinct, and mean, summary.

    14 min read
    3% of exam
    12 sources
    Published 21 Oct 2026
    Docs as of 30 Sep 2026

    What you will be able to do

    • Pick between DataFrame.count(), count("*") and count(column), and predict what each one returns when the data has nulls
    • Compute averages with mean or avg, both on a whole DataFrame and per group with groupBy().agg(), and name the output columns
    • Decide when approx_count_distinct beats an exact distinct count, and what its rsd parameter controls
    • Use describe() and summary() to get several statistics in one call, and choose which statistics summary() returns

    Key concept

    Aggregate function — A function that turns many rows into one value per group. With no groupBy, the whole DataFrame counts as one group. Where you call it decides the shape of the result: a single row from select or agg, or one row per key after groupBy.

    1.Three ways to count, and what each one counts

    Aggregation is how a DataFrame of millions of rows becomes a number you can act on: how many orders came in, the average basket size, how many distinct customers showed up. The simplest aggregation is counting, and Spark gives you three calls for it. They look alike, but they return different types and treat nulls differently.

    **df.count()** is a method on the DataFrame. It returns a plain Python int holding the number of rows. Because it hands back a value rather than a new DataFrame, it is an action. For how that triggers execution, see actions and lazy evaluation.

    **F.count(...)** from pyspark.sql.functions is an aggregate function. It returns a Column that you put inside select or agg, and its result depends on the argument. Pass "*" (as F.count(F.expr("*"))) and it counts every row, nulls included, under the header count(1). Pass a column name and it counts only the rows where that column is not null. In a four-row DataFrame where one alphabets value is None, count(*) gives 4 and count(alphabets) gives 3.

    count on named columns skips nulls: id has 3 values, fruit has 2python
    df.select(sf.count(df.id), sf.count(df.fruit)).show()
    
    +---------+------------+
    |count(id)|count(fruit)|
    +---------+------------+
    |        3|           2|
    +---------+------------+
    The three counts compared
    CallReturnsNullsTypical use
    df.count()int: Number of rowsEvery row countedQuick row total on the driver
    sf.count(sf.expr("*"))Column, shown as count(1)Every row countedRow total inside select or agg, next to other aggregates
    sf.count(df.alphabets)Column, shown as count(alphabets)Rows where the column is null are skippedHow many rows actually have a value in that column

    Counting a column never removes duplicates. If 1,000 rows hold only 40 distinct user_id values, count("user_id") still reports 1,000 when none of them are null. Distinct counts need their own functions, covered further down.

    Checkpoint 1 of 7· Match them up

    A DataFrame has 4 rows, and one alphabets value is null. Match each counting call to what it gives you.

    Tap a term, then the definition that fits it.

    Checkpoint 2 of 7· Exam question

    A DataFrame orders has 1,000 rows, and its discount_code column is null for 300 of them. What does the following code return, and why? orders.select(F.count("discount_code")).collect()[0][0]

    Sources12

    2.Averages with mean and avg, overall or per group

    **mean and avg are the same function under two names.** Both are in pyspark.sql.functions, and both return the average of the values in a group. The output header is always avg(...), even when you call mean. So sf.mean("age") gives a column named avg(age).

    Like count on a column, the average ignores nulls. In the ages None, 2 and 4, the null is skipped, and the result is 3.0 (the average of 2 and 4), not 2.0. A group that is empty or holds only nulls averages to NULL.

    These functions work in two places. Inside select or agg with no grouping, they reduce the whole DataFrame to one row: df.agg(...) is shorthand for df.groupBy().agg(). After groupBy("key"), you get a GroupedData object. It has shortcut methods such as count(), avg(), mean(), min(), max() and sum(), plus a general agg(*exprs).

    The avg shortcut on GroupedData: one row per group, output column named avg(age)python
    df.groupBy("name").avg("age").sort("name").show()
    
    +-----+--------+
    | name|avg(age)|
    +-----+--------+
    |Alice|     2.5|
    |  Bob|     7.5|
    +-----+--------+

    The shortcuts are limited. Each one computes a single kind of statistic, and you can't rename what it produces: groupBy("name").count() always gives a column called count, and .mean("order_total") gives avg(order_total). When you need several statistics side by side with names you choose, use agg. Give it Column expressions, and put .alias(...) on each expression to set its output column name, for example F.count("order_id").alias("order_count") next to F.avg("order_total").alias("avg_total"). agg also takes a dictionary such as {"age": "max"}, but the dictionary form can't attach aliases.

    Checkpoint 3 of 7· Check yourself

    You want one row per region, with the region's average order_total in a column named avg_total. Which code gives you that?

    Checkpoint 4 of 7· Exam question

    A data engineer wants to compute, for each region, the number of orders and the average order_total, with the average column labeled avg_total. Which code produces this result?

    Sources3456

    3.Exact versus approximate distinct counts

    Spark has an exact and an approximate distinct count. count_distinct(col, *cols) returns the exact number of distinct values, shown as count(DISTINCT value). It can take several columns and count distinct combinations. approx_count_distinct(col, rsd=None) returns an estimate instead.

    The estimate comes from the HyperLogLog++ (HLL++) algorithm, which is built for cardinality estimation: working out how many distinct values a column has without keeping a list of them. That's why it suits a user_id column with tens of millions of rows when a dashboard needs to load fast and being off by a few percent doesn't matter. The general rule: approximate aggregates speed up queries and cut costs when you don't need exact results. Two common wrong answers miss the point. count doesn't deduplicate, so it can't give a distinct count. collect_set returns a set of the values themselves, not a number.

    The rsd parameter is the maximum relative standard deviation the estimate may have. It defaults to 0.05, which means results are accurate to within about 5%. A larger rsd allows more error. A very small one cancels out the advantage: once rsd is below 0.01, count_distinct is the more efficient choice.

    Same 100,000 distinct ids, two error bounds: the default rsd and rsd=0.1python
    from pyspark.sql import functions as sf
    spark.range(100000).agg(
        sf.approx_count_distinct("id").alias('with_default_rsd'),
        sf.approx_count_distinct("id", 0.1).alias('with_rsd_0.1')
    ).show()
    
    +----------------+------------+
    |with_default_rsd|with_rsd_0.1|
    +----------------+------------+
    |           95546|      102065|
    +----------------+------------+

    Neither number above is exactly 100,000, and the 0.1 run happens to land above the true value while the default run lands below it. The estimate can miss in either direction. To get an approximate count over several columns, combine them with struct("name", "value") and pass the struct as a single column.

    Checkpoint 5 of 7· Check yourself

    An analyst needs the number of distinct user_id values to within 0.5%, so they plan to call approx_count_distinct("user_id", rsd=0.005). What should they do instead?

    Checkpoint 6 of 7· Exam question

    A data engineer needs the count of distinct values in a user_id column across tens of millions of rows. Exact precision is not required and query latency matters more than accuracy. Which line correctly fills the blank? from pyspark.sql import functions as F result = df.select(F.________("user_id")).collect()[0][0]

    Sources78910

    4.Many statistics in one call: describe() and summary()

    **describe() and summary() compute a set of statistics in one pass and return them as a new DataFrame.** Each statistic is a row, labelled in a summary column, with one column per input column. Both work on numeric and string columns, and both are meant for exploring data. The schema of the result isn't guaranteed to stay the same across versions, so don't build production pipelines on it.

    describe(*cols) always returns the same five statistics: count, mean, stddev, min and max. Its argument chooses which columns to describe, as names or a list, such as df.describe(['age']). With no argument it describes every column.

    summary(*statistics) adds to that in two ways. Called with no arguments, it returns the describe statistics plus approximate percentiles at 25%, 50% and 75%, placed between min and max. And its arguments are statistic names, not column names. You can ask for any subset of count, mean, stddev, min and max, plus any percentile written as a percentage string such as "75%". To limit which columns are summarised, select them first.

    summary() with chosen statistics, run on the columns picked by selectpython
    df.select("age", "weight", "height").summary("count", "min", "25%", "75%", "max").show()
    # +-------+---+------+------+
    # |summary|age|weight|height|
    # +-------+---+------+------+
    # |  count|  3|     3|     3|
    # |    min| 11|  37.8| 142.2|
    # |    25%| 11|  37.8| 142.2|
    # |    75%| 13|  44.1| 150.5|
    # |    max| 13|  44.1| 150.5|
    # +-------+---+------+------+
    describe() and summary() side by side
    Aspectdescribe(*cols)summary(*statistics)
    Arguments nameColumns to describeStatistics to compute
    Default outputcount, mean, stddev, min, maxcount, mean, stddev, min, 25%, 50%, 75%, max
    PercentilesNoYes, any percentage such as 75%
    Restricting columnsPass the column namesselect the columns first

    Checkpoint 7 of 7· Fill the gap

    Which method completes this sample, so that the arguments pick the statistics and the output includes the 25% and 75% percentiles?

    df.select("age", "weight", "height"). ? ("count", "min", "25%", "75%", "max").show()
    # +-------+---+------+------+
    # |summary|age|weight|height|
    # +-------+---+------+------+
    # |  count|  3|     3|     3|
    # |    min| 11|  37.8| 142.2|
    # |    25%| 11|  37.8| 142.2|
    # |    75%| 13|  44.1| 150.5|
    # |    max| 13|  44.1| 150.5|
    # +-------+---+------+------+

    Sources1112

    Sources

    (12)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 2.
      “Returns the number of items in a group.”
      ↩︎ Three ways to count, and what each one counts
      “Count non-null values in a specific column”
      ↩︎ Three ways to count, and what each one counts
      “Count non-null values in a specific column”
      ↩︎ Exam trap 1
      “Count non-null values in multiple columns”
      ↩︎ Prediction
      “Example 2: Count non-null values in a specific column”
      ↩︎ Checkpoint
    2. 3.
      “Returns the average of the values in a group. An alias of avg.”
      ↩︎ Averages with mean and avg, overall or per group
      “Returns the average of the values in a group. An alias of avg.”
      ↩︎ Exam trap 4
    3. 4.
      “Nulls within the group are ignored. If a group is empty or consists only of nulls the result is NULL.”
      ↩︎ Averages with mean and avg, overall or per group
    4. 5.
      “Aggregate on the entire DataFrame without groups (shorthand for df.groupBy().agg()).”
      ↩︎ Averages with mean and avg, overall or per group
      “Aggregate on the entire DataFrame without groups (shorthand for df.groupBy().agg()).”
      ↩︎ Key concept
    5. 6.
      “Computes average values for each numeric column for each group. mean is an alias.”
      ↩︎ Averages with mean and avg, overall or per group
    6. 8.
      “The implementation uses the dense version of the HyperLogLog++ (HLL++) algorithm, a state of the art cardinality estimation algorithm.”
      ↩︎ Exact versus approximate distinct counts
    7. 9.
      “The maximum allowed relative standard deviation (default = 0.05). If rsd < 0.01, it would be more efficient to use count_distinct.”
      ↩︎ Exact versus approximate distinct counts
      “If rsd < 0.01, it would be more efficient to use count_distinct.”
      ↩︎ Exam trap 2
      “If rsd < 0.01, it would be more efficient to use count_distinct.”
      ↩︎ Checkpoint
    8. 10.
      “using approximation for aggregates can accelerate query processing and reduce costs when you don't require precise results.”
      ↩︎ Exact versus approximate distinct counts
    9. 11.
      “Available statistics are: count, mean, stddev, min, max, arbitrary approximate percentiles specified as a percentage (e.g., 75%).”
      ↩︎ Many statistics in one call: describe() and summary()
      “This function is meant for exploratory data analysis, as we make no guarantee about the backward compatibility of the schema of the resulting DataFrame.”
      ↩︎ Many statistics in one call: describe() and summary()
    10. 12.
      “Computes basic statistics for numeric and string columns.”
      ↩︎ Many statistics in one call: describe() and summary()
      “Column name or list of column names to describe by (default All columns).”
      ↩︎ Exam trap 3
      “Use summary for expanded statistics and control over which statistics to compute.”
      ↩︎ Prediction

    Ready to test yourself?

    Practise Databricks Certified Associate Developer for Apache Spark in quiz mode.

    Spotted a mistake, or was something unclear? Tell us.