DATABRICKS-CERTIFIED-ASSOCIATE-DEVELOPER-FOR-APACHE-SPARK-3-0 practice question 25 of 25

Which of the following code blocks reorders the values inside the arrays in column attributes of DataFrame itemsDf from last to first one in the…

Full set: 180 questions
Which of the following code blocks reorders the values inside the arrays in column attributes of DataFrame itemsDf from last to first one in the alphabet? 1. +------+-----------------------------+-------------------+ 2. |itemId|attributes |supplier | 3. +------+-----------------------------+-------------------+ 4. |1 |[blue, winter, cozy] |Sports Company Inc.| 5. |2 |[red, summer, fresh, cooling]|YetiX | 6. |3 |[green, summer, travel] |Sports Company Inc.| 7. +------+-----------------------------+-------------------+
Answer options
A: itemsDf.withColumn('attributes', sort_array(col('attributes').desc()))
B: itemsDf.withColumn('attributes', sort_array(desc('attributes')))
C: itemsDf.withColumn('attributes', sort(col('attributes'), asc=False))
D: itemsDf.withColumn("attributes", sort_array("attributes", asc=False)) Correct answer
E: itemsDf.select(sort_array("attributes"))
Correct Answer:
D. itemsDf.withColumn("attributes", sort_array("attributes", asc=False))
Explanation

Output of correct code block: +------+-----------------------------+-------------------+ |itemId|attributes |supplier | +------+-----------------------------+-------------------+ |1 |[winter, cozy, blue] |Sports Company Inc.| |2 |[summer, red, fresh, cooling]|YetiX | |3 |[travel, summer, green] |Sports Company Inc.| +------+-----------------------------+-------------------+ It can be confusing to differentiate between the different sorting functions in PySpark. In this case, a particularity about sort_array has to be considered: The sort direction is given by the second argument, not by the desc method. Luckily, this is documented in the documentation (link below). Also, for solving this Question: you need to understand the difference between sort and sort_array. With sort, you cannot sort values in arrays. Also, sort is a method of DataFrame, while sort_array is a method of pyspark.sql.functions. More info: pyspark.sql.functions.sort_array — PySpark 3.1.2 documentation Static notebook | Dynamic notebook: See test 2,

Scroll to Top