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.
df.select(sf.count(df.id), sf.count(df.fruit)).show()
+---------+------------+
|count(id)|count(fruit)|
+---------+------------+
| 3| 2|
+---------+------------+| Call | Returns | Nulls | Typical use |
|---|---|---|---|
| df.count() | int: Number of rows | Every row counted | Quick row total on the driver |
| sf.count(sf.expr("*")) | Column, shown as count(1) | Every row counted | Row 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 skipped | How 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.
df.count() is a DataFrame method that returns an int. sf.count is an aggregate that returns a Column. With "*" it counts every row, and with a column name it counts only the non-null values in that column.
“Example 2: Count non-null values in a specific column”Source: docs.databricks.com
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]
Correct answer: D — 700, because count applied to a named column counts only the non-null values in that column, excluding the 300 rows where it is null.
- A.
count()works perfectly well with a column name; the wildcard form is an alternative for counting all rows including nulls, not a requirement for the function to operate. - B. Counting every row regardless of nulls is the behavior of
count("*")ordf.count(), notcount()on a specific column, so this overstates the result. - C. Counting a column reports how many values are present, not how many are missing, so this has the logic inverted and would undercount the actual result.
- D. This is correct: counting a named column skips rows where that column is null, so only the 700 rows with a non-null discount code are tallied.
- E. Aggregate functions in Spark are designed to handle nulls directly, so no preceding
dropna()call is needed forcountto execute successfully.
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).
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.
Without a groupBy before it, agg aggregates the whole DataFrame and collapses it to one row with no region column left. Grouping has to come first: orders.groupBy("region").agg(...).
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?
Grouping first and then calling agg with an aliased expression gives one row per region and the column name you chose. mean is an alias of avg, so the shortcut names its output avg(order_total) and a rename of "mean(order_total)" matches nothing. A select with no groupBy collapses the data to a single row. The dictionary form can't attach aliases, so .alias() there names the DataFrame, not the column.
“Computes average values for each numeric column for each group. mean is an alias.”Source: docs.databricks.com
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?
Correct answer: C — orders.groupBy("region").agg(
F.count("order_id").alias("order_count"),
F.avg("order_total").alias("avg_total")
)
which passes both named aggregates to .agg() after grouping, giving each output column its own alias.
- A. Calling
.agg()first collapses the DataFrame into a single aggregated row before any grouping is applied, so chaining.groupBy()afterward has no grouping keys left to operate on and does not produce a per-region breakdown. - B.
.count()only returns a row count per group with a fixed column name, and calling.alias()on the resulting DataFrame does not rename a column or add an average, so this does not meet the requirement. - C. This is correct:
.agg()after.groupBy()accepts multiple named aggregate expressions, and each.alias()controls the output column label independently, producing the exact two-column report requested. - D.
.mean()on a grouped DataFrame names its own output columnavg(order_total)and produces noorder_countcolumn, so renaming a nonexistentorder_countcolumn has no effect and the count is missing entirely. - E. Mixing an unaggregated grouping key with aggregate expressions inside
.select()and then calling.groupBy()afterward is not the pattern Spark expects; aggregate expressions must be resolved through.agg()alongside the grouping columns, not after a plain.select().
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.
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?
rsd only caps the estimate's relative standard deviation and never makes it exact. Once rsd is below 0.01, approximating costs more than it saves, so the exact count_distinct is the better choice. count doesn't remove duplicates, and collect_set returns the values themselves, not a number.
“If rsd < 0.01, it would be more efficient to use count_distinct.”Source: docs.databricks.com
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]
Correct answer: B — approx_count_distinct("user_id"), which relies on the HyperLogLog++ algorithm to estimate cardinality within a bounded relative error, trading exact precision for a single-pass, low-memory computation.
- A. This produces the exact distinct count but requires shuffling and deduplicating the full dataset, which is the cost the scenario explicitly wants to avoid, so it is not the best fit even though the result would be correct.
- B. This is correct: the HyperLogLog++-based approximate estimator is designed for exactly this scenario, returning a cardinality estimate with a configurable relative error while avoiding the shuffle a fully exact computation would require.
- C. This counts non-null occurrences without removing duplicates, so it answers a different question than distinct cardinality and would overcount whenever the same
user_idappears more than once. - D. This returns an array of unique values rather than a scalar count, and collecting every distinct value to the driver is far more expensive than either an exact or approximate count.
- E. This is a conditional sum over non-null rows, which is mathematically equivalent to a plain count of non-null values, not a distinct count, so it does not solve the cardinality problem at all.
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.
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|
# +-------+---+------+------+| Aspect | describe(*cols) | summary(*statistics) |
|---|---|---|
| Arguments name | Columns to describe | Statistics to compute |
| Default output | count, mean, stddev, min, max | count, mean, stddev, min, 25%, 50%, 75%, max |
| Percentiles | No | Yes, any percentage such as 75% |
| Restricting columns | Pass the column names | select 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|
# +-------+---+------+------+summary takes statistic names as its arguments, and those can include percentiles such as "25%". describe takes column names and always returns count, mean, stddev, min and max, with no percentiles. agg expects aggregate Column expressions or a dictionary, not statistic names. That is why the columns are picked with select first.
Source: docs.databricks.comSources
(12)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“Returns the number of rows in this DataFrame.”
↩︎ Three ways to count, and what each one counts - 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 - 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 - 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 - 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 - 6.
“Computes average values for each numeric column for each group. mean is an alias.”
↩︎ Averages with mean and avg, overall or per group - 7.
“Returns a new Column for distinct count of col or cols.”
↩︎ Exact versus approximate distinct counts - 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 - 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 - 10.
“using approximation for aggregates can accelerate query processing and reduce costs when you don't require precise results.”
↩︎ Exact versus approximate distinct counts - 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() - 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