DATABRICKS-CERTIFIED-ASSOCIATE-DEVELOPER-FOR-APACHE-SPARK · Question #56
Which of the following code blocks returns a DataFrame where column divisionDistinct is the approximate number of distinct values in column division from DataFrame storesDF?
The correct answer is C. storesDF.agg(approx_count_distinct(col("division")).alias("divisionDistinct")). approx_count_distinct() is an aggregate function from pyspark.sql.functions. Aggregate functions must be used inside agg() or groupBy().agg(), and the result should be aliased. The correct code is storesDF.agg(approx_count_distinct(col('division')).alias('divisionDistinct'))…
Question
Which of the following code blocks returns a DataFrame where column divisionDistinct is the approximate number of distinct values in column division from DataFrame storesDF?
Options
- AstoresDF.withColumn("divisionDistinct", approx_count_distinct(col("division")))
- BstoresDF.agg(col("division").approx_count_distinct("divisionDistinct"))
- CstoresDF.agg(approx_count_distinct(col("division")).alias("divisionDistinct"))
- DstoresDF.withColumn("divisionDistinct", col("division").approx_count_distinct())
- EstoresDF.agg(col("division").approx_count_distinct().alias("divisionDistinct"))
How the community answered
(42 responses)- A14% (6)
- B7% (3)
- C74% (31)
- D2% (1)
- E2% (1)
Explanation
approx_count_distinct() is an aggregate function from pyspark.sql.functions. Aggregate functions must be used inside agg() or groupBy().agg(), and the result should be aliased. The correct code is storesDF.agg(approx_count_distinct(col('division')).alias('divisionDistinct')). Option C matches this exactly. Option A uses withColumn with an aggregate function, which produces incorrect behavior (same aggregated value repeated per row, not a single summary row). Options B, D, and E incorrectly try to call approx_count_distinct() as a method on a Column object, which does not exist.
Topics
Community Discussion
No community discussion yet for this question.