Which of the following code blocks returns approximately 1000 rows, some of them potentially being duplicates, from the 2000-row DataFrame transactionsDf that only has unique rows?
-
A
transactionsDf.sample(True, 0.5)
-
B
transactionsDf.take(1000).distinct()
-
C
transactionsDf.sample(False, 0.5)
-
D
transactionsDf.take(1000)
-
E
transactionsDf.sample(True, 0.5, force=True)
Reveal answer details
Close answer details
Correct answerA
ExplanationIn transactionsDf.sample(True, 0.5), True enables sampling with replacement, so an original row may be selected more than once. The fraction 0.5 gives an expected sample size near half of 2000, or approximately 1000 rows. Because sampling is probabilistic, the count is approximate rather than fixed.
Which of the following code blocks will always return a new 4-partition DataFrame from the 8-partition DataFrame storesDF without inducing a shuffle?
-
A
storesDF.repartition(4, "sqft")
-
B
-
C
-
D
-
E
Reveal answer details
Close answer details
Correct answerC
ExplanationstoresDF.coalesce(4) reduces the existing eight partitions to four by combining them through a narrow transformation, avoiding a full shuffle. The target is lower than the current partition count, which fits coalesce's intended direction. repartition variants redistribute records and therefore induce the shuffle excluded by the question.
A data engineer is working on a Spark job that reads data from a large text file, applies a filter to remove invalid records, and then groups the data by a specific column. After writing the results in a table, the engineer wants to understand the execution pattern of the Spark job to optimize its performance. What is the sequence of operations in the Spark job?
-
A
The Spark job reads the entire text file into memory, applies the filter, and then groups the data by the specified column.
-
B
The Spark job reads the text file, applies the filter as an action, and then groups the data by the specified column as a transformation.
-
C
The Spark job reads the text file lazily, applies the filter and grouping as a single transformation, and then executes the entire pipeline as an action.
-
D
The Spark job reads the text file lazily, applies the filter as a narrow transformation, and then groups the data by the specified column as a wide transformation, causing a shuffle.
Reveal answer details
Close answer details
Correct answerD
ExplanationReading constructs the DataFrame lazily, and the filter remains a narrow transformation because each output partition can be derived from one input partition without redistribution. Grouping by a column is a wide transformation: records sharing a key must be brought together across partitions, causing a shuffle. Writing the table is the action that triggers execution of this planned pipeline.
What is the main advantage of using DataFrame over RDD in Spark?
-
A
DataFrames provide better low-level control over data processing
-
B
DataFrames are faster due to Catalyst optimizer and Tungsten execution
-
C
DataFrames support more programming languages than RDDs
-
D
DataFrames have simpler API with fewer operations
Reveal answer details
Close answer details
Correct answerB
ExplanationDataFrames expose schema-aware relational operations that Catalyst can analyze and optimize before execution. Tungsten improves the physical execution of those plans, including memory and code-generation behavior. RDD operations provide lower-level control but do not give these optimizers the same structured information, so DataFrames can execute faster.
Which of the following code blocks returns a DataFrame containing exactly one row when applied to transactionsDf? Full DataFrame transactionsDf: 1.+-------------+---------+-----+-------+---------+----+ 2.|transactionId|predError|value|storeId|productId| f| 3.+-------------+---------+-----+-------+---------+----+ 4.| 1| 3| 4| 25| 1|null| 5.| 2| 6| 7| 2| 2|null| 6.| 3| 3| null| 25| 3|null| 7.| 4| null| null| 3| 2|null| 8.| 5| null| null| null| 2|null| 9.| 6| 3| 2| 25| 2|null| 10.+-------------+---------+-----+-------+---------+----+
-
A
transactionsDf.where(col("storeId").between(3,25))
-
B
transactionsDf.filter((col("storeId")!=25) | (col("productId")==2))
-
C
transactionsDf.filter(col("storeId")==25).select("predError","storeId").distinct()
-
D
transactionsDf.select("productId", "storeId").where("storeId == 2 OR storeId != 25")
-
E
transactionsDf.where(col("value").isNull()).select("productId", "storeId").distinct()
Reveal answer details
Close answer details
Correct answerC
ExplanationFiltering for storeId == 25 keeps three rows. Selecting only predError and storeId makes each of those rows the identical pair (3, 25). The final distinct() removes the duplicate pairs, so transactionsDf yields a DataFrame containing exactly one row.
Given the schema:  event_ts TIMESTAMP, sensor_id STRING, metric_value LONG, ingest_ts TIMESTAMP, source_file_path STRING The goal is to deduplicate based on: event_ts, sensor_id, and metric_value.
-
A
dropDuplicates on all columns (wrong criteria)
-
B
dropDuplicates with no arguments (removes based on all columns)
-
C
groupBy without aggregation (invalid use)
-
D
dropDuplicates on the exact matching fields
Reveal answer details
Close answer details
Correct answerD
ExplanationDeduplication must use exactly event_ts, sensor_id, and metric_value as the matching fields. Passing that subset to dropDuplicates treats records with the same three business values as duplicates even when ingest_ts or source_file_path differs, retaining one representative row.
Which of the following code blocks does NOT return a DataFrame sorted alphabetically in ascending order by the division column?
-
A
storesDF.sort(asc("division"))
-
B
storesDF.orderBy(["division"], ascending = [1])
-
C
storesDF.orderBy(col("division").desc())
-
D
storesDF.orderBy("division")
-
E
storesDF.sort("division")
Reveal answer details
Close answer details
Correct answerC
ExplanationstoresDF.orderBy(col("division").desc()) explicitly requests descending order for division, placing later alphabetical values before earlier ones. The required result is ascending alphabetical order. A plain sort or orderBy on the column uses ascending order, and asc() or ascending=[1] also states that direction explicitly.
A data engineer is working on num_df DataFrame: num_df = spark.range(5).toDF("num") The engineer is using the Python UDF: def cubefunc(val): return val ** 3 Which code fragment registers and uses this UDF as a Spark SQL function to work with the DataFrame num_df?
-
A
spark.udf.register("cubeudf", cubefunc, IntegerType()) num_df.selectExpr("cubeudf(num)")
-
B
cubeudf = udf (cubefunc) num_df.select(cubeudf(col("num")))
-
C
spark.udf.register("cubeudf", cubefunc, DoubleType()) num_df.selectExpr("cubeudf(num)")
-
D
cubeudf = udf(cubefunc) num_df.selectExpr(cubeudf(num)")
Reveal answer details
Close answer details
Correct answerA
Explanationspark.udf.register("cubeudf", cubefunc, IntegerType()) registers the Python function under a SQL-visible name and declares its integer result type. Because the input values are 0 through 4, their cubes fit that type. num_df.selectExpr("cubeudf(num)") then invokes the registered SQL function against column num.
Which of the following code blocks returns a new DataFrame where column productCategories only has one word per row, resulting in a DataFrame with many more rows than DataFrame storesDF? A sample of storesDF is displayed below: 
-
A
storesDF.withColumn("productCategories", explode(col("productCategories")))
-
B
storesDF.withColumn("productCategories", split(col("productCategories")))
-
C
storesDF.withColumn("productCategories", col("productCategories").explode())
-
D
storesDF.withColumn("productCategories", col("productCategories").split())
-
E
storesDF.withColumn("productCategories", explode("productCategory"))
Reveal answer details
Close answer details
Question 10
Single choice
Which of the following cluster configurations is most likely to experience delays due to garbage collection of a large Dataframe?  Note: each configuration has roughly the same compute power using 100GB of RAM and 200 cores.
-
A
More information is needed to determine an answer.
-
B
-
C
-
D
-
E
Reveal answer details
Close answer details
Correct answerD
ExplanationScenario #1 places all 100 GB of executor memory and all 200 cores in one executor. A large executor heap gives garbage collection a larger memory region to manage, so collection pauses can be longer and affect all work in that executor. Splitting the same resources among smaller executors reduces each individual heap's collection burden.
Question 11
Single choice
The code block shown below contains an error. The code block is intended to return a new 12-partition DataFrame from the 8-partition DataFrame storesDF by inducing a shuffle. Identify the error. Code block: storesDF.coalesce(12)
-
A
The coalesce() operation cannot guarantee the number of target partitions - the repartition() operation should be used instead.
-
B
The coalesce() operation does not induce a shuffle and cannot increase the number of partitions - the repartition() operation should be used instead.
-
C
The coalesce() operation will only work if the DataFrame has been cached to memory - the repartition() operation should be used instead.
-
D
The coalesce() operation requires a column by which to partition rather than a number of partitions - the repartition() operation should be used instead.
-
E
The number of resulting partitions, 12, is not achievable for an 8-partition DataFrame.
Reveal answer details
Close answer details
Correct answerB
Explanationcoalesce() is designed to reduce partitions without a shuffle; it cannot expand an 8-partition DataFrame into 12 partitions as requested. repartition(12) performs the necessary shuffle and creates a new DataFrame with the requested partition count. The issue is therefore both the direction of the change and the required shuffle behavior.
Question 12
Single choice
The code block shown below contains an error. The code block intended to return a new DataFrame that is the result of an inner join between DataFrame storesDF and DataFrame employeesDF on column storeId. Identify the error. Code block: storesDF.join(employeesDF, "inner", "storeId")
-
A
The key column storeID needs to be wrapped in the col() operation.
-
B
The key column storeID needs to be in a list like ["storeID"].
-
C
The key column storeID needs to be specified in an expression of both DataFrame columns like storesDF.storeId == employeesDF.storeId.
-
D
There is no DataFrame.join() operation - DataFrame.merge() should be used instead.
-
E
The column key is the second parameter to join() and the type of join in the third parameter to join() - the second and third arguments should be switched.
Reveal answer details
Close answer details
Question 13
Single choice
A data engineer is running a Spark job to process a dataset of 1 TB stored in distributed storage. The cluster has 10 nodes, each with 16 CPUs. Spark UI shows: Low number of Active Tasks Many tasks complete in milliseconds Fewer tasks than available CPUs Which approach should be used to adjust the partitioning for optimal resource allocation?
-
A
Set the number of partitions equal to the total number of CPUs in the cluster
-
B
Set the number of partitions to a fixed value, such as 200
-
C
Set the number of partitions equal to the number of nodes in the cluster
-
D
Set the number of partitions by dividing the dataset size (1 TB) by a reasonable partition size, such as 128 MB
Reveal answer details
Close answer details
Correct answerD
ExplanationPartition count should be derived from the volume of data and a reasonable target partition size. Dividing the 1 TB dataset by a size such as 128 MB creates enough partitions to keep the cluster's CPUs supplied with tasks while avoiding a few oversized partitions. A fixed count based only on nodes or CPUs ignores the dataset's scale.
Question 14
Single choice
Which of the following describes characteristics of the Spark driver?
-
A
The Spark driver requests the transformation of operations into DAG computations from the worker nodes.
-
B
If set in the Spark configuration, Spark scales the Spark driver horizontally to improve parallel processing performance.
-
C
The Spark driver processes partitions in an optimized, distributed fashion.
-
D
In a non-interactive Spark application, the Spark driver automatically creates the SparkSession object.
-
E
The Spark driver's responsibility includes scheduling queries for execution on worker nodes.
Reveal answer details
Close answer details
Correct answerE
ExplanationThe driver coordinates an application rather than processing distributed partitions itself. It builds and schedules work, then assigns executable tasks to worker-side executors. Scheduling queries for execution on worker nodes is therefore part of the driver's responsibility, while the workers perform the partition-level computation.
Question 15
Single choice
The code block shown below should return a new 4-partition DataFrame from the 8-partition DataFrame storesDF without inducing a shuffle. Choose the response that correctly fills in the numbered blanks within the code block to complete this task. Code block: _1_._2_(_3_)
-
A
1. storesDF 2. coalesce 3. Nothing
-
B
1. storesDF 2. coalesce 3. 4
-
C
1. storesDF 2. coalesce 3. 4, "storeId"
-
D
1. storesDF 2. coalesce 3. "storeId"
Reveal answer details
Close answer details
Correct answerB
ExplanationstoresDF.coalesce(4) reduces the existing eight partitions to four by combining current partitions, normally without redistributing every record through a full shuffle. The target partition count is the required argument. A column name is unnecessary because coalesce changes partition quantity rather than partitioning the data by a key.
Question 16
Single choice
Which of the following operations returns a GroupedData object?
-
A
-
B
-
C
-
D
-
E
Reveal answer details
Close answer details
Correct answerD
ExplanationDataFrame.groupBy() defines one or more grouping expressions and returns a GroupedData object. That intermediate object exposes aggregate operations such as count(), sum(), and agg(), which then produce a DataFrame. Calling groupBy() alone establishes the grouping; it does not yet calculate an aggregate result.
Question 17
Single choice
Which of the following describes a shuffle?
-
A
A shuffle is a process that is executed during a broadcast hash join.
-
B
A shuffle is a process that compares data across executors.
-
C
A shuffle is a process that compares data across partitions.
-
D
A shuffle is a Spark operation that results from DataFrame.coalesce().
-
E
A shuffle is a process that allocates partitions to executors.
Reveal answer details
Close answer details
Correct answerC
ExplanationA shuffle moves and reorganizes records across partition boundaries so records that must be compared or combined can meet in the appropriate destination partitions. This cross-partition exchange underlies operations such as grouped aggregation and many joins. It is not merely executor allocation, and a normal partition-reducing coalesce does not inherently require it.
Question 18
Single choice
Which of the following describes Spark's standalone deployment mode?
-
A
Standalone mode uses a single JVM to run Spark driver and executor processes.
-
B
Standalone mode means that the cluster does not contain the driver.
-
C
Standalone mode is how Spark runs on YARN and Mesos clusters.
-
D
Standalone mode uses only a single executor per worker per application.
-
E
Standalone mode is a viable solution for clusters that run multiple frameworks, not only Spark.
Reveal answer details
Close answer details
Correct answerD
ExplanationIn Spark standalone deployment, each application uses one executor process on each worker assigned to that application, with that executor running multiple tasks through its allocated cores. The driver and executors remain separate processes rather than sharing one JVM. This per-worker, per-application executor model identifies the stated standalone characteristic.
Question 19
Single choice
What is the purpose of the spark.sql.adaptive.enabled configuration in Spark 3.0+?
-
A
To automatically adjust the number of shuffle partitions based on data size
-
B
To enable automatic broadcasting of small tables in joins
-
C
To optimize the logical plan of SQL queries before execution
-
D
To handle skew in join operations by splitting small partitions
Reveal answer details
Close answer details
Question 20
Single choice
The code block displayed below contains an error. When the code block below has executed, it should have divided DataFrame transactionsDf into 14 parts, based on columns storeId and transactionDate (in this order). Find the error. Code block: transactionsDf.coalesce(14, "storeId", "transactionDate")
-
A
The parentheses around the column names need to be removed and .select() needs to be appended to the code block.
-
B
Operator coalesce needs to be replaced by repartition, the parentheses around the column names need to be removed, and .count() needs to be appended to the code block.
-
C
Operator coalesce needs to be replaced by repartition, the parentheses around the column names need to be removed, and .select() needs to be appended to the code block.
-
D
Operator coalesce needs to be replaced by repartition and the parentheses around the column names need to be replaced by square brackets.
-
E
Operator coalesce needs to be replaced by repartition.
Reveal answer details
Close answer details
Correct answerE
Explanation
repartition() can create a specified number of partitions while partitioning the DataFrame according to one or more columns. Therefore, repartition(14, "storeId", "transactionDate") creates 14 partitions using storeId and transactionDate as partitioning expressions. coalesce() is intended primarily to reduce the number of partitions and does not accept partitioning columns.
Question 21
Single choice
Which command overwrites an existing JSON file when writing a DataFrame?
-
A
df.write.mode("overwrite").json("path/to/file")
-
B
df.write.overwrite.json("path/to/file")
-
C
df.write.json("path/to/file", overwrite=True)
-
D
df.write.format("json").save("path/to/file", mode="append")
Reveal answer details
Close answer details
Correct answerA
Explanationdf.write.mode("overwrite").json("path/to/file") uses the standard PySpark DataFrameWriter API to write a DataFrame in JSON format while setting the save mode to overwrite. When the target path already contains data, overwrite mode replaces the existing output with the newly written DataFrame. The mode() method configures the write behavior before json() performs the actual JSON write operation.
Question 22
Single choice
Which of the following statements about the Spark DataFrame is true?
-
A
Spark DataFrames are mutable unless they've been collected to the driver.
-
B
A Spark DataFrame is rarely used aside from the import and export of data.
-
C
Spark DataFrames cannot be distributed into partitions.
-
D
A Spark DataFrame is a tabular data structure that is the most common Structured API in Spark.
-
E
A Spark DataFrame is exactly the same as a data frame in Python or R.
Reveal answer details
Close answer details
Correct answerD
ExplanationA Spark DataFrame represents tabular data through named columns and is the central structure used by Spark's Structured APIs. Its rows are distributed across partitions and transformations return new DataFrames rather than mutating the existing one. Similarity to Python or R tables does not make their execution and distribution models identical.
Question 23
Single choice
Which of the following statements about Spark's execution hierarchy is correct?
-
A
In Spark's execution hierarchy, a job may reach over multiple stage boundaries.
-
B
In Spark's execution hierarchy, manifests are one layer above jobs.
-
C
In Spark's execution hierarchy, a stage comprises multiple jobs.
-
D
In Spark's execution hierarchy, executors are the smallest unit.
-
E
In Spark's execution hierarchy, tasks are one layer above slots.
Reveal answer details
Close answer details
Correct answerA
ExplanationAn action creates a Spark job, and shuffle dependencies can divide that job into multiple stages. Each stage then consists of tasks that perform its partition-level work. Thus, one job can extend across multiple stage boundaries; a stage does not contain multiple jobs, and an executor is a runtime process rather than the smallest work unit.
Question 24
Single choice
Which of the following code blocks returns a one-column DataFrame of all values in column supplier of DataFrame itemsDf that do not contain the letter X? In the DataFrame, every value should only be listed once. Sample of DataFrame itemsDf: 1.+------+--------------------+--------------------+-------------------+ 2.|itemId| itemName| attributes| supplier| 3.+------+--------------------+--------------------+-------------------+ 4.| 1|Thick Coat for Wa...|[blue, winter, cozy]|Sports Company Inc.| 5.| 2|Elegant Outdoors ...|[red, summer, fre...| YetiX| 6.| 3| Outdoors Backpack|[green, summer, t...|Sports Company Inc.| 7.+------+--------------------+--------------------+-------------------+
-
A
itemsDf.filter(col(supplier).not_contains('X')).select(supplier).distinct()
-
B
itemsDf.select(~col('supplier').contains('X')).distinct()
-
C
itemsDf.filter(not(col('supplier').contains('X'))).select('supplier').unique()
-
D
itemsDf.filter(~col('supplier').contains('X')).select('supplier').distinct()
-
E
itemsDf.filter(!col('supplier').contains('X')).select(col('supplier')).unique()
Reveal answer details
Close answer details
Correct answerD
ExplanationitemsDf.filter(~col('supplier').contains('X')) negates the contains predicate, retaining supplier values without the letter X. select('supplier') then reduces the result to the requested single column, and distinct() removes repeated supplier rows. The PySpark negation operator for a Column is ~, while unique() is not the DataFrame deduplication method.
Question 25
Single choice
Which of the following code blocks stores DataFrame itemsDf in executor memory and, if insufficient memory is available, serializes it and saves it to disk?
-
A
itemsDf.persist(StorageLevel.MEMORY_ONLY)
-
B
itemsDf.cache(StorageLevel.MEMORY_AND_DISK)
-
C
-
D
-
E
itemsDf.write.option('destination', 'memory').save()
Reveal answer details
Close answer details
Correct answerD
ExplanationitemsDf.cache() marks the DataFrame for persistence using the DataFrame cache storage level, which uses executor memory and can store partitions on disk when they do not fit. Caching is lazy, so storage is populated when an action evaluates itemsDf. MEMORY_ONLY would instead recompute partitions that cannot remain in memory rather than save them to disk.
Question 26
Single choice
Which of the following statements about executors is correct, assuming that one can consider each of the JVMs working as executors as a pool of task execution slots?
-
A
Slot is another name for executor.
-
B
There must be less executors than tasks.
-
C
An executor runs on a single core.
-
D
There must be more slots than tasks.
-
E
Tasks run in parallel via slots.
Reveal answer details
Close answer details
Correct answerE
ExplanationAn executor can be viewed as providing a pool of slots, with each available slot able to run a task. Multiple occupied slots allow tasks from a stage to run in parallel, subject to available executor resources. A slot is therefore capacity within an executor rather than another name for the executor, and task count need not equal slot count.
Question 27
Single choice
Which of the following code blocks returns a single-column DataFrame showing the number of words in column supplier of DataFrame itemsDf? Sample of DataFrame itemsDf: 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.+------+-----------------------------+-------------------+
-
A
itemsDf.split("supplier", " ").count()
-
B
itemsDf.split("supplier", " ").size()
-
C
itemsDf.select(word_count("supplier"))
-
D
spark.select(size(split(col(supplier), " ")))
-
E
itemsDf.select(size(split("supplier", " ")))
Reveal answer details
Close answer details
Correct answerE
Explanationsplit("supplier", " ") turns each supplier string into an array separated at spaces. Applying size returns the number of elements in that array for each row. Wrapping the expression in itemsDf.select(...) produces the requested single-column DataFrame rather than collecting one global count.
Question 28
Single choice
Which of the following statements about slots is incorrect?
-
A
Slots are the most granular level of execution in the Spark execution hierarchy.
-
B
Slots are resources for parallelization within an executor.
-
C
Tasks are assigned to slots for computation.
-
D
There can be more slots than tasks.
-
E
There must be at least as many slots as there are executors.
Reveal answer details
Close answer details
Correct answerA
ExplanationA slot represents an executor's capacity to run one task concurrently; it is a resource, not a level of executable work in Spark's hierarchy. Tasks are the most granular scheduled units. The number of slots can exceed the current number of tasks, and executors provide one or more slots for task computation.
Question 29
Single choice
Which of the following code blocks returns a 10 percent sample of rows from DataFrame storesDF with replacement?
-
A
-
B
storesDF.sample(true, fraction = 0.1)
-
C
storesDF.sample(true, fraction = 0.15)
-
D
storesDF.sampleBy(fraction = 0.1)
-
E
storesDF.sample(false, fraction = 0.1)
Reveal answer details
Close answer details
Correct answerB
ExplanationstoresDF.sample(true, fraction = 0.1) sets sampling with replacement to true and uses 0.1 as the sampling fraction, representing 10 percent. With replacement means a source row can be selected more than once. Setting the first argument to false would sample without replacement, and 0.15 would request 15 percent.
Question 30
Single choice
Which of the following describes the role of tasks in the Spark execution hierarchy?
-
A
Tasks are the smallest element in the execution hierarchy.
-
B
Within one task, the slots are the unit of work done for each partition of the data.
-
C
Tasks are the second-smallest element in the execution hierarchy.
-
D
Stages with narrow dependencies can be grouped into one task.
-
E
Tasks with wide dependencies can be grouped into one stage.
Reveal answer details
Close answer details
Correct answerA
ExplanationA job is divided into stages, and each stage is divided into tasks. A task is the smallest scheduled element in this execution hierarchy and performs the stage's work for a partition. Executor slots are resources that run tasks, not smaller units nested inside a task, so they do not replace tasks as the hierarchy's work element.
Question 31
Single choice
Which of the following DataFrame operators is never classified as a wide transformation?
-
A
-
B
-
C
-
D
-
E
Reveal answer details
Close answer details
Correct answerD
ExplanationDataFrame.select() projects expressions or columns independently within each existing partition. Each output partition can be computed from its corresponding input partition, so no redistribution of records is required and the dependency is narrow. Sorting, repartitioning, aggregation, and many joins can require cross-partition shuffles and become wide.
Question 32
Single choice
Which of the following code blocks will most quickly return an approximation for the number of distinct values in column division in DataFrame storesDF?
-
A
storesDF.agg(approx_count_distinct(col("division")).alias("divisionDistinct"))
-
B
storesDF.agg(approx_count_distinct(col("division"), 0.01).alias("divisionDistinct"))
-
C
storesDF.agg(approx_count_distinct(col("division"), 0.15).alias("divisionDistinct"))
-
D
storesDF.agg(approx_count_distinct(col("division"), 0.0).alias("divisionDistinct"))
-
E
storesDF.agg(approx_count_distinct(col("division"), 0.05).alias("divisionDistinct"))
Reveal answer details
Close answer details
Correct answerC
ExplanationThe second approx_count_distinct argument controls relative standard deviation: a larger value permits a less precise estimate with less computational work. Among the listed explicit settings, 0.15 allows the greatest error and therefore favors the quickest approximation. The aggregation then returns that estimate under the divisionDistinct alias.
Question 33
Single choice
The code block shown below should return a column that indicates through boolean variables whether rows in DataFrame transactionsDf have values greater or equal to 20 and smaller or equal to 30 in column storeId and have the value 2 in column productId. Choose the answer that correctly fills the blanks in the code block to accomplish this. transactionsDf.__1__((__2__.__3__) __4__ (__5__))
-
A
1. select 2. col("storeId") 3. between(20, 30) 4. and 5. col("productId")==2
-
B
1. where 2. col("storeId") 3. geq(20).leq(30) 4. & 5. col("productId")==2
-
C
1. select 2. "storeId" 3. between(20, 30) 4. && 5. col("productId")==2
-
D
1. select 2. col("storeId") 3. between(20, 30) 4. && 5. col("productId")=2
-
E
1. select 2. col("storeId") 3. between(20, 30) 4. & 5. col("productId")==2
Reveal answer details
Close answer details
Correct answerE
ExplanationBlank 1 is select, blank 2 is col("storeId"), and blank 3 is between(20, 30), which includes both range boundaries. The boolean column expression is combined with col("productId") == 2 by the & operator. Parentheses preserve the intended grouping of the two conditions.
Question 34
Single choice
You have: DataFrame A: 128 GB of transactions DataFrame B: 1 GB user lookup table Which strategy is correct for broadcasting?
-
A
DataFrame B should be broadcasted because it is smaller and will eliminate the need for shuffling itself
-
B
DataFrame B should be broadcasted because it is smaller and will eliminate the need for shuffling DataFrame A
-
C
DataFrame A should be broadcasted because it is larger and will eliminate the need for shuffling DataFrame B
-
D
DataFrame A should be broadcasted because it is smaller and will eliminate the need for shuffling itself
Reveal answer details
Close answer details
Correct answerB
ExplanationDataFrame B is the smaller 1 GB lookup table, so it is the appropriate broadcast side. Replicating B to executors lets each partition of the 128 GB DataFrame A perform its lookup locally. This eliminates the need to shuffle the much larger DataFrame A by join key, which is the principal benefit of the strategy.
Question 35
Single choice
Which of the following operations can be used to rename and replace an existing column in a DataFrame?
-
A
DataFrame.renamedColumn()
-
B
DataFrame.withColumnRenamed()
-
C
-
D
-
E
Reveal answer details
Close answer details
Correct answerB
ExplanationDataFrame.withColumnRenamed() returns a new DataFrame in which an existing column name is replaced by the requested new name. The column's values remain associated with that renamed field. col() only constructs a column reference, while the other listed names are not the DataFrame renaming operation.
Question 36
Single choice
Which of the following object types cannot be contained within a column of a Spark DataFrame?
-
A
-
B
-
C
-
D
-
E
Reveal answer details
Close answer details
Correct answerA
ExplanationA DataFrame is itself a distributed tabular collection with a schema, not a scalar or structured field value that can be stored inside one of its own columns. Columns can represent supported values such as strings, arrays, vectors, and nulls according to their declared data types. Nested tabular data must instead be represented through supported structured types.
Question 37
Single choice
A data engineer is working on the DataFrame:  (Referring to the table image: it has columnsId,Name,count, andtimestamp. ) Which code fragment should the engineer use to extract the unique values in theNamecolumn into an alphabetically ordered list?
-
A
df.select("Name").orderBy(df["Name"].asc())
-
B
df.select("Name").distinct().orderBy(df["Name"])
-
C
df.select("Name").distinct()
-
D
df.select("Name").distinct().orderBy(df["Name"].desc())
Reveal answer details
Close answer details
Correct answerB
Explanationdf.select("Name").distinct().orderBy(df["Name"]) first keeps only the Name column, then removes repeated names with distinct(). The final orderBy uses the default ascending direction, producing the unique names in alphabetical order. Sorting without distinct would leave duplicates in the result.
Question 38
Single choice
Which of the following code blocks creates a Python UDF assessPerformanceUDF() using the integer-returning Python function assessPerformance() and applies it to Column customerSatisfaction in DataFrame storesDF?
-
A
assessPerformanceUDF = udf(assessPerformance, IntegerType) storesDF.withColumn("result", assessPerformanceUDF(col("customerSatisfaction")))
-
B
assessPerformanceUDF = udf(assessPerformance, IntegerType()) storesDF.withColumn("result", assessPerformanceUDF(col("customerSatisfaction")))
-
C
assessPerformanceUDF - udf(assessPerformance) storesDF.withColumn("result", assessPerformance(col("customerSatisfaction")))
-
D
assessPerformanceUDF = udf(assessPerformance) storesDF.withColumn("result", assessPerformanceUDF(col("customerSatisfaction")))
-
E
assessPerformanceUDF = udf(assessPerformance, IntegerType()) storesDF.withColumn("result", assessPerformance(col("customerSatisfaction")))
Reveal answer details
Close answer details
Correct answerB
Explanationudf(assessPerformance, IntegerType()) wraps the Python function and declares an instantiated integer return type. The resulting assessPerformanceUDF is then called on col("customerSatisfaction") inside storesDF.withColumn("result", ...). This applies the UDF per row and stores its integer output in the result column.
Question 39
Single choice
A Spark developer is developing a Spark application to monitor task performance across a cluster. One of the application's requirements is to track the maximum processing time for tasks on each worker node and consolidate this information on the driver for further analysis. Which technique should the developer use to achieve this?
-
A
Use an RDD action like reduce () to compute the maximum time.
-
B
Use an accumulator to record the maximum time on the driver.
-
C
Broadcast a variable to share the maximum time among workers.
-
D
Configure the Spark UI to automatically collect maximum times.
Reveal answer details
Close answer details
Correct answerB
ExplanationAn accumulator provides a worker-to-driver aggregation path: tasks contribute processing-time observations, and the resulting accumulated state is available on the driver. Using a maximum-aware accumulator retains the largest time needed for analysis. A broadcast variable instead distributes read-only state from the driver to workers.
Question 40
Single choice
Which of the following code blocks returns a DataFrame showing the mean value of column "value" of DataFrame transactionsDf, grouped by its column storeId?
-
A
transactionsDf.groupBy(col(storeId).avg())
-
B
transactionsDf.groupBy("storeId").avg(col("value"))
-
C
transactionsDf.groupBy("storeId").agg(avg("value"))
-
D
transactionsDf.groupBy("storeId").agg(average("value"))
-
E
transactionsDf.groupBy("value").average()
Reveal answer details
Close answer details
Correct answerC
ExplanationtransactionsDf.groupBy("storeId") establishes one group for each distinct storeId. The following agg(avg("value")) computes the arithmetic mean of value separately within every group and returns the grouping key with the aggregate. Calling agg without groupBy would calculate one mean over the complete DataFrame rather than one per store.
Question 41
Single choice
How can a Spark developer ensure optimal resource utilization when running Spark jobs in Local Mode for testing?
-
A
Configure the application to run in cluster mode instead of local mode.
-
B
Increase the number of local threads based on the number of CPU cores.
-
C
Use the spark.dynamicAllocation.enabled property to scale resources dynamically.
-
D
Set the spark.executor.memory property to a large value.
Reveal answer details
Close answer details
Correct answerB
ExplanationLocal Mode executes Spark work through threads on one machine. Increasing the number of local threads to reflect the available CPU cores allows more tasks to run concurrently during testing and makes better use of that machine. Executor memory and dynamic allocation do not determine local task-level CPU parallelism.
Question 42
Single choice
Which of the following operations will always return a new DataFrame with updated partitions from DataFrame storesDF by inducing a shuffle?
-
A
-
B
storesDF.rdd.getNumPartitions()
-
C
-
D
-
E
Reveal answer details
Close answer details
Correct answerC
Explanationrepartition() creates a new DataFrame with the requested partitioning and performs a shuffle so records can move between partitions. coalesce() is intended mainly to reduce partitions without a full shuffle, getNumPartitions() only reports a count, and the other operations do not guarantee repartitioning through a shuffle.
Question 43
Single choice
In which order should the code blocks shown below be run in order to create a DataFrame that shows the mean of column predError of DataFrame transactionsDf per column storeId and productId, where productId should be either 2 or 3 and the returned DataFrame should be sorted in ascending order by column storeId, leaving out any nulls in that column? DataFrame transactionsDf: 1.+-------------+---------+-----+-------+---------+----+ 2.|transactionId|predError|value|storeId|productId| f| 3.+-------------+---------+-----+-------+---------+----+ 4.| 1| 3| 4| 25| 1|null| 5.| 2| 6| 7| 2| 2|null| 6.| 3| 3| null| 25| 3|null| 7.| 4| null| null| 3| 2|null| 8.| 5| null| null| null| 2|null| 9.| 6| 3| 2| 25| 2|null| 10.+-------------+---------+-----+-------+---------+----+ 1. .mean("predError") 2. .groupBy("storeId") 3. .orderBy("storeId") 4. transactionsDf.filter(transactionsDf.storeId.isNotNull()) 5. .pivot("productId", [2, 3])
-
A
-
B
-
C
-
D
-
E
Reveal answer details
Close answer details
Correct answerD
ExplanationStep 4 removes rows with null storeId. Step 2 groups the remaining rows by that field, and step 5 pivots on productId using only values 2 and 3. Step 1 computes the mean of predError for each group and pivot value, after which step 3 orders the result by storeId ascending.
Question 44
Single choice
Which of the following operations can be used to return the number of rows in a DataFrame?
-
A
-
B
-
C
-
D
-
E
DataFrame.countDistinct()
Reveal answer details
Close answer details
Correct answerD
ExplanationDataFrame.count() is an action that evaluates the DataFrame and returns its total row count as a number. It does not produce a per-column count or a count of unique values. countDistinct is an aggregation for distinct expressions, while the other named operations are not the DataFrame row-count action.
Question 45
Single choice
The code block shown below should add column transactionDateForm to DataFrame transactionsDf. The column should express the unix-format timestamps in column transactionDate as string type like Apr 26 (Sunday). Choose the answer that correctly fills the blanks in the code block to accomplish this. transactionsDf.__1__(__2__, from_unixtime(__3__, __4__))
-
A
1. withColumn 2. "transactionDateForm" 3. "MMM d (EEEE)" 4. "transactionDate"
-
B
1. select 2. "transactionDate" 3. "transactionDateForm" 4. "MMM d (EEEE)"
-
C
1. withColumn 2. "transactionDateForm" 3. "transactionDate" 4. "MMM d (EEEE)"
-
D
1. withColumn 2. "transactionDateForm" 3. "transactionDate" 4. "MM d (EEE)"
-
E
1. withColumnRenamed 2. "transactionDate" 3. "transactionDateForm" 4. "MM d (EEE)"
Reveal answer details
Close answer details
Correct answerC
ExplanationwithColumn adds "transactionDateForm" while retaining the rest of transactionsDf. from_unixtime takes "transactionDate" as its timestamp input and "MMM d (EEEE)" as its formatting pattern. MMM creates the abbreviated month, d the day number, and EEEE the full weekday name, yielding text such as Apr 26 (Sunday).
Question 46
Single choice
The code block shown below contains an error. The code is intended to print the schema of DataFrame storesDF. Identify the error. storesDF.printSchema().getAs[String]
-
A
printSchema() is not a member of DataFrame; getSchema() should be used instead.
-
B
printSchema() is not a member of DataFrame; schema() should be used instead.
-
C
The entire expression must be converted to a string before it can be printed.
-
D
printSchema() already prints the DataFrame schema and does not return a Row, so getAs[String] cannot be called on its result.
-
E
The schema must first be retrieved with schema and then passed to print().
Reveal answer details
Close answer details
Correct answerD
ExplanationprintSchema() performs the printing itself and does not return a Row containing schema data. Its result therefore cannot be followed by getAs[String], which is a Row field-access operation. The complete operation is simply storesDF.printSchema(); retrieving schema as a value would require a different expression rather than chaining Row access.
Question 47
Single choice
Which of the following code blocks returns a new DataFrame where column managerName from DataFrame storesDF has had its missing values replaced with the value "No Manager"? A sample of DataFrame storesDF is below: 
-
A
storesDF.na.fill("No Manager", "managerName")
-
B
storesDF.nafill("No Manager", col("managerName"))
-
C
storesDF.na.fill("No Manager", col("managerName"))
-
D
storesDF.fillna("No Manager", col("managerName"))
-
E
storesDF.nafill("No Manager", "managerName")
Reveal answer details
Close answer details
Correct answerA
ExplanationstoresDF.na.fill("No Manager", "managerName") uses the DataFrame null-handling API, supplies the replacement value, and limits the replacement to managerName. Existing non-null manager names remain unchanged, while null entries become "No Manager". The column selector is passed as a column name rather than a col object.
Question 48
Single choice
Which of the following code blocks returns a DataFrame containing only the rows from DataFrame storesDF where the value in column sqft is less than or equal to 25,000 OR the value in column customerSatisfaction is greater than or equal to 30?
-
A
storesDF.filter(col("sqft") <= 25000 | col("customerSatisfaction") >= 30)
-
B
storesDF.filter(col("sqft") <= 25000 or col("customerSatisfaction") >= 30)
-
C
storesDF.filter(sqft <= 25000 or customerSatisfaction >= 30)
-
D
storesDF.filter(col(sqft) <= 25000 | col(customerSatisfaction) >= 30)
-
E
storesDF.filter((col("sqft") <= 25000) | (col("customerSatisfaction") >= 30))
Reveal answer details
Close answer details
Correct answerE
Explanationfilter() requires a Column expression that evaluates to true for retained rows. col("sqft") and col("customerSatisfaction") create the two column references, and | combines their parenthesized comparisons with column-wise OR. Thus a row survives when sqft is at most 25000, customerSatisfaction is at least 30, or both.
Question 49
Single choice
Which of the following code blocks creates a new DataFrame with two columns season and wind_speed_ms where column season is of data type string and column wind_speed_ms is of data type double?
-
A
spark.DataFrame({"season": ["winter","summer"], "wind_speed_ms": [4.5, 7.5]})
-
B
spark.createDataFrame([("summer", 4.5), ("winter", 7.5)], ["season", "wind_speed_ms"])
-
C
1. from pyspark.sql import types as T 2. spark.createDataFrame((("summer", 4.5), ("winter", 7.5)),
-
D
StructType([T.StructField("season", T.CharType()), T.StructField("season",
-
E
-
F
spark.newDataFrame([("summer", 4.5), ("winter", 7.5)], ["season", "wind_speed_ms"])
-
G
spark.createDataFrame({"season": ["winter","summer"], "wind_speed_ms": [4.5, 7.5]})
Reveal answer details
Close answer details
Correct answerB
Explanationspark.createDataFrame receives rows [("summer", 4.5), ("winter", 7.5)] and the matching column-name list ["season", "wind_speed_ms"]. Schema inference identifies summer and winter as string values and 4.5 and 7.5 as double values. Each two-element tuple maps positionally to the two requested columns.
Question 50
Single choice
The code block displayed below contains an error. The code block is intended to write DataFrame transactionsDf to disk as a parquet file in location /FileStore/transactions_split, using column storeId as key for partitioning. Find the error. Code block: transactionsDf.write.format("parquet").partitionOn("storeId").save("/FileStore/transactions_s plit")A.
-
A
The format("parquet") expression is inappropriate to use here, "parquet" should be passed as first argument to the save() operator and "/FileStore/transactions_split" as the second argument.
-
B
Partitioning data by storeId is possible with the partitionBy expression, so partitionOn should be replaced by partitionBy.
-
C
Partitioning data by storeId is possible with the bucketBy expression, so partitionOn should be replaced by bucketBy.
-
D
partitionOn("storeId") should be called before the write operation.
-
E
The format("parquet") expression should be removed and instead, the information should be added to the write expression like so: write("parquet").
Reveal answer details
Close answer details
Correct answerB
ExplanationThe DataFrameWriter method for directory partitioning is partitionBy, not partitionOn. Replacing that call yields write.format("parquet").partitionBy("storeId").save(...), which writes Parquet data into partitions keyed by storeId. The format and save portions already have the appropriate roles and do not need to be moved.
Question 51
Single choice
A data engineer is working with a dataset containing 2 billion rows distributed across 10 Spark partitions. The engineer needs to compute the approximate count of distinct users by their 'user_id' field and also calculate the average value of 'transaction_amount'. Both calculations must be done in a single transformation step to minimize shuffling. Which set of Spark code will achieve this goal while ensuring performance?
-
A
from pyspark.sql.functions import approx_count_distinct, avg df.agg ( approx_count_distinct ("user_id") .alias ("approx_count_distinct"), avg("transaction_amount").alias ("average_transaction") ).show()
-
B
from pyspark.sql.functions import count Distinct, avg df.agg ( count Distinct ("user_id").alias ("approx_count_distinct"), avg("transaction_amount").alias ("average_transaction") ).show()
-
C
df.creareOrReplaceTempView("transactions") spark.sql(""" SELECT - COUNT(DISTINCT user_id) AS approx._count_distinct, AVG(transaction_amount) AS average_transaction FROM transactions - """).show()
-
D
from pyspark.sql.functions import col approx._count = df.select ("user_id").distinct().count() average_transaction = df.select("transaction_amount").groupBy().avg().collect() [0] [0] print(approx_count, average_transaction)
Reveal answer details
Close answer details
Correct answerA
ExplanationThe PySpark SQL functions approx_count_distinct and avg can be imported and evaluated together by one df.agg. The first function computes an approximate count for user_id, while the second calculates the average transaction_amount. Combining both aggregate expressions avoids separate distinct and average pipelines and supports the requested single aggregation step.
Question 52
Single choice
Which of the following code blocks immediately removes the previously cached DataFrame transactionsDf from memory and disk?
-
A
array_remove(transactionsDf, "*")
-
B
transactionsDf.unpersist()
-
C
-
D
transactionsDf.clearCache()
-
E
Reveal answer details
Close answer details
Correct answerB
ExplanationtransactionsDf.unpersist() explicitly removes the DataFrame's persisted cache blocks from its configured storage locations, including memory and disk. It reverses a previous cache or persist request without deleting the DataFrame variable or its underlying source data. persist() would request caching rather than release it.
Question 53
Single choice
Which of the following describes why garbage collection in Spark is important?
-
A
Logical results will be incorrect if inaccurate data is not collected and removed from the Spark job.
-
B
Spark jobs will fail or run slowly if inaccurate data is not collected and removed from the Spark job.
-
C
Spark jobs will fail or run slowly if memory is not available for new objects to be created.
-
D
Spark jobs will produce inaccurate results if there are too many different transformations called before a single action.
-
E
Spark jobs will produce inaccurate results if memory is not available for new tasks to run and complete.
Reveal answer details
Close answer details
Correct answerC
ExplanationGarbage collection reclaims heap space occupied by objects that are no longer reachable. Spark continuously needs memory for objects created while tasks execute, so failure to reclaim enough space causes frequent collection pauses, poor performance, or an out-of-memory failure. It concerns memory management, not removing inaccurate records.
Question 54
Single choice
The code block displayed below contains an error. The code block should write DataFrame transactionsDf as a parquet file to location filePath after partitioning it on column storeId. Find the error. Code block: transactionsDf.write.partitionOn("storeId").parquet(filePath)
-
A
The partitioning column as well as the file path should be passed to the write() method of DataFrame transactionsDf directly and not as appended commands as in the code block.
-
B
The partitionOn method should be called before the write method.
-
C
The operator should use the mode() option to configure the DataFrameWriter so that it replaces any existing files at location filePath.
-
D
Column storeId should be wrapped in a col() operator.
-
E
No method partitionOn() exists for the DataFrame class, partitionBy() should be used instead.
Reveal answer details
Close answer details
Correct answerE
ExplanationPartitioned file output is configured on the DataFrameWriter returned by transactionsDf.write. Its method for choosing partition columns is partitionBy, not partitionOn. The valid chain is therefore transactionsDf.write.partitionBy("storeId").parquet(filePath).
Question 55
Single choice
An engineer has a large ORC file located at/file/test_data.orcand wants to read only specific columns to reduce memory usage. Which code fragment will select the columns, i.e. ,col1,col2, during the reading process?
-
A
spark.read.orc("/file/test_data.orc").filter("col1 = 'value' ").select("col2")
-
B
spark.read.format("orc").select("col1", "col2").load("/file/test_data.orc")
-
C
spark.read.orc("/file/test_data.orc").selected("col1", "col2")
-
D
spark.read.format("orc").load("/file/test_data.orc").select("col1", "col2")
Reveal answer details
Close answer details
Correct answerD
Explanationspark.read.format("orc").load("/file/test_data.orc").select("col1", "col2") uses the valid reader sequence: specify the ORC format, load the file into a DataFrame, and select the required columns. Spark can apply column pruning to the ORC scan, reducing the data read and retained for this query.
Question 56
Single choice
Which of the following describes the main difference between inner join and left outer join?
-
A
Inner join returns only matching rows, left outer join returns all rows from left table
-
B
Inner join returns all rows from both tables, left outer join returns only matching rows
-
C
Inner join is faster but less accurate than left outer join
-
D
Inner join requires both tables to have the same schema, left outer join doesn't
Reveal answer details
Close answer details
Correct answerA
ExplanationAn inner join emits rows only when the join condition finds a match on both sides. A left outer join preserves every row from the left table; when no right-side match exists, its right-side fields are null. The distinction is therefore which unmatched rows survive, not schema equality, accuracy, or an inherent speed guarantee.
Question 57
Single choice
Which of the following describes how Spark achieves fault tolerance?
-
A
Spark helps fast recovery of data in case of a worker fault by providing the MEMORY_AND_DISK storage level option.
-
B
If an executor on a worker node fails while calculating an RDD, that RDD can be recomputed by another executor using the lineage.
-
C
Spark builds a fault-tolerant layer on top of the legacy RDD data system, which by itself is not fault tolerant.
-
D
Due to the mutability of DataFrames after transformations, Spark reproduces them using observed lineage in case of worker node failure.
-
E
Spark is only fault-tolerant if this feature is specifically enabled via the spark.fault_recovery.enabled property.
Reveal answer details
Close answer details
Correct answerB
ExplanationRDDs retain lineage describing how their partitions were derived. If an executor fails while calculating an RDD partition, Spark can schedule the lost work on another executor and recompute the partition from that lineage. Fault tolerance therefore comes from reproducible derivation rather than mutable copies or a special enablement property.
Question 58
Single choice
Which of the following describes the main purpose of Spark's Catalyst optimizer?
-
A
To manage cluster resources and schedule tasks across executors
-
B
To optimize and execute logical plans for Spark SQL and DataFrame operations
-
C
To handle fault tolerance by recomputing lost data partitions
-
D
To manage memory usage and spill data to disk when necessary
Reveal answer details
Close answer details
Correct answerB
ExplanationCatalyst processes Spark SQL and DataFrame logical plans, applies analysis and optimization rules, and turns the optimized result into an executable physical plan. This can improve operations without changing their declared result. Resource allocation, task scheduling, fault recovery, and memory spilling belong to other Spark components.
Question 59
Single choice
Which of the following code blocks returns a DataFrame where column managerName from DataFrame storesDF is split at the space character into column managerFirstName and column managerLastName? A sample of DataFrame storesDF is displayed below: 
-
A
(storesDF.withColumn("managerFirstName", split(col("managerName"), " ")[0]) .withColumn("managerLastName", split(col("managerName"), " ")[1]))
-
B
(storesDF.withColumn("managerFirstName", col("managerName"). split(" ")[1]) .withColumn("managerLastName", col("managerName").split(" ")[2]))
-
C
(storesDF.withColumn("managerFirstName", split(col("managerName"), " ")[1]) .withColumn("managerLastName", split(col("managerName"), " ")[2]))
-
D
(storesDF.withColumn("managerFirstName", col("managerName").split(" ")[0]) .withColumn("managerLastName", col("managerName").split(" ")[1]))
-
E
(storesDF.withColumn("managerFirstName", split("managerName"), " ")[0]) .withColumn("managerLastName", split("managerName"), " ")[1]))
Reveal answer details
Close answer details
Correct answerA
Explanationsplit(col("managerName"), " ") produces an array of name parts. Spark array positions are zero-based, so index 0 supplies managerFirstName and index 1 supplies managerLastName. Chaining two storesDF.withColumn calls creates both columns while retaining the original DataFrame columns.
Question 60
Single choice
Which of the following describes a way for resizing a DataFrame from 16 to 8 partitions in the most efficient way?
-
A
Use operation DataFrame.repartition(8) to shuffle the DataFrame and reduce the number of partitions.
-
B
Use operation DataFrame.coalesce(8) to fully shuffle the DataFrame and reduce the number of partitions.
-
C
Use a narrow transformation to reduce the number of partitions.
-
D
Use a wide transformation to reduce the number of partitions.
-
E
Use operation DataFrame.coalesce(0.5) to halve the number of partitions in the DataFrame.
Reveal answer details
Close answer details
Correct answerC
ExplanationReducing partitions can use coalesce(8), which normally forms a narrow dependency and avoids redistributing every record across the network. A full repartition(8) shuffle can also reach eight partitions but performs substantially more data movement. The narrow transformation is therefore the efficient resizing approach.
Question 61
Single choice
A developer needs to write the output of a complex chain of Spark transformations to a Parquet table called events.live_latest. The consumers of this Parquet table primarily access this table with a Spark SQL query with a WHERE clause that filters by both the year and month of the event_ts column. The event_ts column is of TIMESTAMP type. The following code is initially deployed but the downstream consumers have complained about poor read performance.  Which change will enable efficient querying by the downstream consumers of the table on both the year and the month in the event_ts column?
-
A
Replace .bucketBy() with .partitionBy("event_year")
-
B
Replace .bucketBy() with .partitionBy (["event_year", "event_month"])
-
C
Change the first value in .bucketBy() from 42 to a lower number
-
D
Add .sortBy("event_month") after .bucketBy()
Reveal answer details
Close answer details
Correct answerB
ExplanationThe consumers filter by both derived values, event_year and event_month. Replacing bucketBy with partitionBy(["event_year", "event_month"]) lays out the Parquet table by those filter columns, allowing Spark to prune unrelated year-month partitions during reads. Bucketing or sorting does not provide the same direct partition elimination for these predicates.
Question 62
Single choice
Which of the following code blocks returns a single-row DataFrame that only has a column corr which shows the Pearson correlation coefficient between columns predError and value in DataFrame transactionsDf?
-
A
transactionsDf.select(corr(["predError", "value"]).alias("corr")).first()
-
B
transactionsDf.select(corr(col("predError"), col("value")).alias("corr")).first()
-
C
transactionsDf.select(corr(predError, value).alias("corr"))
-
D
transactionsDf.select(corr(col("predError"), col("value")).alias("corr"))
-
E
transactionsDf.select(corr("predError", "value"))
Reveal answer details
Close answer details
Correct answerD
Explanationcorr(col("predError"), col("value")) constructs the Pearson correlation aggregate over the two numeric columns. Because it is an aggregate with no grouping, select returns one row. alias("corr") supplies the required output name while preserving the result as a DataFrame; calling first() would extract a Row instead.
Question 63
Single choice
Which of the following code blocks returns a DataFrame where rows in DataFrame storesDF containing missing values in every column have been dropped?
-
A
-
B
-
C
storesDF.na.drop("all", subset = "sqft")
-
D
-
E
Reveal answer details
Close answer details
Correct answerD
ExplanationstoresDF.na.drop("all") applies the null-dropping operation with the rule that every column in a row must be missing before that row is removed. A row containing at least one non-null value remains. Calling drop without "all" uses a stricter rule and can remove rows that have only some values missing.
Question 64
Single choice
The code block displayed below contains an error. The code block should combine data from DataFrames itemsDf and transactionsDf, showing all rows of DataFrame itemsDf that have a matching value in column itemId with a value in column transactionsId of DataFrame transactionsDf. Find the error. Code block: itemsDf.join(itemsDf.itemId==transactionsDf.transactionId)
-
A
The join statement is incomplete.
-
B
The union method should be used instead of join.
-
C
The join method is inappropriate.
-
D
The merge method should be used instead of join.
-
E
The join expression is malformed.
Reveal answer details
Close answer details
Correct answerA
ExplanationThe join condition correctly compares itemsDf.itemId with transactionsDf.transactionId, but the statement is incomplete because join also needs the other DataFrame as its first argument. Supplying transactionsDf identifies the right side of the join; the equality expression then determines matching rows.
Question 65
Single choice
The code block displayed below contains an error. The code block should arrange the rows of DataFrame transactionsDf using information from two columns in an ordered fashion, arranging first by column value, showing smaller numbers at the top and greater numbers at the bottom, and then by column predError, for which all values should be arranged in the inverse way of the order of items in column value. Find the error. Code block: transactionsDf.orderBy('value', asc_nulls_first(col('predError')))
-
A
Two orderBy statements with calls to the individual columns should be chained, instead of having both columns in one orderBy statement.
-
B
Column value should be wrapped by the col() operator.
-
C
Column predError should be sorted in a descending way, putting nulls last.
-
D
Column predError should be sorted by desc_nulls_first() instead.
-
E
Instead of orderBy, sort should be used.
Reveal answer details
Close answer details
Correct answerC
ExplanationThe first sort key, 'value', is ascending by default, which places smaller non-null values before greater ones. The second key must use descending order because its direction is the inverse, and nulls must be placed last. Replacing asc_nulls_first(col('predError')) with a descending, nulls-last expression supplies that required secondary ordering.
Question 66
Single choice
Which of the following code blocks writes DataFrame storesDF to file path filePath as text files?
-
A
-
B
storesDF.write.path(filePath)
-
C
storesDF.write().text(filePath)
-
D
storesDF.write.text(filePath)
-
E
storesDF.write.option("text").path(filePath)
Reveal answer details
Close answer details
Correct answerD
ExplanationstoresDF.write returns a DataFrameWriter, and its text(filePath) method selects the text output format and destination in one call. Therefore storesDF.write.text(filePath) forms the required writer chain. Calling write as a function or using path without selecting a supported output method does not express the same text write.
Question 67
Single choice
Which feature of Spark Connect is considered when designing an application to enable remote interaction with the Spark cluster?
-
A
It provides a way to run Spark applications remotely in any programming language
-
B
It can be used to interact with any remote cluster using the REST API
-
C
It allows for remote execution of Spark jobs
-
D
It is primarily used for data ingestion into Spark from external sources
Reveal answer details
Close answer details
Correct answerC
ExplanationSpark Connect separates the client application from the Spark cluster and allows the client to submit DataFrame operations for remote execution. The cluster executes the resulting Spark jobs while the application interacts from another process or machine. This capability is distinct from using Spark primarily as an external-source ingestion mechanism.
Question 68
Single choice
Which code should be used to display the schema of the parquet file stored in the location events_parquet?
-
A
spark.sql("SELECT * FROM " + events_parquet + "").printSchema ()
-
B
spark.sql("SELECT * FROM parquet.`" + events_parquet + "`").printSchema()
-
C
spark.sql("SELECT * FROM " + events_parquet + "").show()
-
D
spark.sql("SELECT * FROM parquet. " +events_parquet + " ").show()
Reveal answer details
Close answer details
Question 69
Single choice
Which of the following operations is most likely to cause data skew if the key column has uneven distribution?
-
A
-
B
-
C
-
D
Reveal answer details
Close answer details
Correct answerC
ExplanationgroupBy() brings records with the same key together so each group can be aggregated. If key frequencies are uneven, one or a few resulting partitions may receive far more rows than the others, creating data skew and slow straggler tasks. Simple column selection, removal, or row filtering does not group records by key.
Question 70
Single choice
The code block shown below contains an error. The code block is intended to return a new DataFrame where column managerName from DataFrame storesDF is split at the space character into column managerFirstName and column managerLastName. Identify the error. A sample of DataFrame storesDF is displayed below:  Code block: storesDF.withColumn("managerFirstName", col("managerName").split(" ").getItem(0)) .withColumn("managerLastName", col("managerName").split(" ").getItem(1))
-
A
The index values of 0 and 1 are not correct - they should be 1 and 2, respectively.
-
B
The index values of 0 and 1 should be provided as second arguments to the split() operation rather than indexing the result.
-
C
The split() operation comes from the imported functions object. It accepts only a string column name and split character as arguments. It is not a method of a Column object.
-
D
The split() operation comes from the imported functions object. It accepts a Column object and split character as arguments. It is not a method of a Column object.
-
E
The withColumn operation cannot be called twice in a row.
Reveal answer details
Close answer details
Question 71
Single choice
Which of the following statements about executors is correct?
-
A
Executors are launched by the driver.
-
B
Executors stop upon application completion by default.
-
C
Each node hosts a single executor.
-
D
Executors store data in memory only.
-
E
An executor can serve multiple applications.
Reveal answer details
Close answer details
Correct answerB
ExplanationExecutors are application-specific processes that run tasks and hold data for the lifetime of a Spark application. When that application completes, its executors stop by default and their resources return to the cluster manager. They are not shared concurrently by multiple applications, nor are they restricted to storing data only in memory.
Question 72
Single choice
The code block shown below should write DataFrame storesDF to file path filePath as parquet and partition by values in column division. Choose the response that correctly fills in the numbered blanks within the code block to complete this task. Code block: storesDF.__1__.__2__(__3__).__4__(__5__)
-
A
1. write 2. partitionBy 3. "division" 4. path 5. filePath, node = parquet
-
B
1. write 2. partitionBy 3. "division" 4. parquet 5. filePath
-
C
1. write 2. partitionBy 3. col("division") 4. parquet 5. filePath
-
D
1. write() 2. partitionBy 3. col("division") 4. parquet 5. filePath
-
E
1. write 2. repartition 3. "division" 4. path 5. filePath, mode = "parquet"
Reveal answer details
Close answer details
Correct answerB
ExplanationThe completed chain is storesDF.write.partitionBy("division").parquet(filePath). write creates the writer, partitionBy uses the string column name to organize output into directories by division value, and parquet writes the resulting partitioned data at filePath in Parquet format.
Question 73
Single choice
Which of the following code blocks removes all rows in the 6-column DataFrame transactionsDf that have missing data in at least 3 columns?
-
A
transactionsDf.dropna("any")
-
B
transactionsDf.dropna(thresh=4)
-
C
transactionsDf.drop.na("",2)
-
D
transactionsDf.dropna(thresh=2)
-
E
transactionsDf.dropna("",4)
Reveal answer details
Close answer details
Correct answerB
ExplanationA six-column row missing at least three values has at most three non-null values. dropna(thresh=4) retains only rows containing at least four non-null values, so every row with three or more missing fields is removed. A threshold of 2 would keep many such incomplete rows, while dropna("any") would also remove rows with only one missing value.
Question 74
Single choice
The code block shown below should extract the integer value for column sqft from the first row of DataFrame storesDF. Choose the response that correctly fills in the numbered blanks within the code block to complete this task. Code block: __1__.__2__.__3__[Int](__4__)
-
A
1. storesDF 2. first() 3. getAs() 4. "sqft"
-
B
1. storesDF 2. first 3. getAs 4. sqft
-
C
1. storesDF 2. first() 3. getAs 4. col("sqft")
-
D
1. storesDF 2. first 3. getAs 4. "sqft"
Reveal answer details
Close answer details
Correct answerD
ExplanationThe completed Scala expression is storesDF.first.getAs[Int]("sqft"). storesDF is the DataFrame, first returns its first Row, and getAs[Int] extracts a field from that Row as an integer. The string "sqft" identifies the field by name; a Column expression is not the required Row accessor argument.
Question 75
Single choice
Which of the following cluster configurations is least likely to experience delays due to garbage collection of a large DataFrame?  Note: each configuration has roughly the same compute power using 100GB of RAM and 200 cores.
-
A
-
B
-
C
-
D
More information is needed to determine an answer.
-
E
Reveal answer details
Close answer details
Correct answerE
ExplanationScenario #6 divides the same total 100 GB of memory and 200 cores among eight executors, each with a 12.5 GB heap and 25 cores. Garbage collection operates on these smaller heaps independently, reducing the duration and impact of any one collection pause. This makes it the least exposed configuration among those listed.
Question 76
Single choice
The code block shown below should return all rows of DataFrame itemsDf that have at least 3 items in column itemNameElements. Choose the answer that correctly fills the blanks in the code block to accomplish this. Example of DataFrame itemsDf: 1.+------+----------------------------------+-------------------+------------------------------------------+ 2.|itemId|itemName |supplier |itemNameElements | 3.+------+----------------------------------+-------------------+------------------------------------------+ 4.|1 |Thick Coat for Walking in the Snow|Sports Company Inc.|[Thick, Coat, for, Walking, in, the, Snow]| 5.|2 |Elegant Outdoors Summer Dress |YetiX |[Elegant, Outdoors, Summer, Dress] | 6.|3 |Outdoors Backpack |Sports Company Inc.|[Outdoors, Backpack] | 7.+------+----------------------------------+-------------------+------------------------------------------+ Code block: itemsDf.__1__(__2__(__3__)__4__)
-
A
1. select 2. count 3. col("itemNameElements") 4. >3
-
B
1. filter 2. count 3. itemNameElements 4. >=3
-
C
1. select 2. count 3. "itemNameElements" 4. >3
-
D
1. filter 2. size 3. "itemNameElements" 4. >=3
-
E
1. select 2. size 3. "itemNameElements" 4. >3
Reveal answer details
Close answer details
Correct answerD
ExplanationBlank 1 uses filter because complete rows must be retained conditionally. Blank 2 uses size on blank 3, "itemNameElements", to calculate each array's element count. Blank 4 applies >= 3, so arrays containing exactly three elements are included along with larger arrays.
Question 77
Single choice
Which of the following code blocks returns a DataFrame containing only the rows from DataFrame storesDF where the value in column sqft is less than or equal to 25,000?
-
A
storesDF.where(storesDF[sqft] > 25000)
-
B
storesDF.filter(sqft > 25000)
-
C
storesDF.filter("sqft" <= 25000)
-
D
storesDF.filter(col("sqft") <= 25000)
-
E
storesDF.where(sqft > 25000)
Reveal answer details
Close answer details
Correct answerD
Explanationcol("sqft") constructs a Spark Column reference, and <= 25000 builds the Boolean column expression required by filter(). filter() retains precisely the rows for which that expression evaluates to true. Quoting only "sqft" and comparing it in the host language would compare a string rather than values from the sqft column.
Question 78
Single choice
Which of the following represents the highest level in Spark’s job execution hierarchy?
-
A
-
B
-
C
-
D
-
E
Reveal answer details
Close answer details
Correct answerB
ExplanationA Spark action creates a job, which is the highest unit in the execution hierarchy listed here. Spark divides that job into stages at shuffle boundaries, and each stage contains tasks that process partitions. Executors and slots are resources that run those tasks, rather than higher-level units of work.
Question 79
Single choice
A data scientist at a financial services company is working with a Spark DataFrame containing transaction records. The DataFrame has millions of rows and includes columns fortransaction_id,account_number,transaction_amount, andtimestamp. Due to an issue with the source system, some transactions were accidentally recorded multiple times with identical information across all fields. The data scientist needs to remove rows with duplicates across all fields to ensure accurate financial reporting. Which approach should the data scientist use to deduplicate the orders using PySpark?
-
A
-
B
df = df.groupBy("transaction_id").agg(F.first("account_number"), first("transaction_amount"), F.first ("timestamp"))
-
C
df = df.filter(F.col("transaction_id").isNotNull())
-
D
df = df.dropDuplicates(["transaction_amount"])
Reveal answer details
Close answer details
Correct answerA
Explanationdf = df.dropDuplicates() removes duplicate rows by comparing every column because no subset is supplied. Thus, records that repeat the same transaction ID, account number, amount, and timestamp collapse to one row. Deduplicating only on transaction amount would incorrectly merge otherwise different transactions.
Question 80
Single choice
A Spark developer wants to improve the performance of an existing PySpark UDF that runs a hash function that is not available in the standard Spark functions library. The existing UDF code is:  The developer wants to replace this existing UDF with a Pandas UDF to improve performance. The developer changes the definition of shake_256_udf to this: shake_256_udf = sf.pandas_udf(shake_256, StringType()) However, the developer receives the error: [UNSUPPORTED_SIGNATURE] Unsupported signature: (raw: str) -> str. What should the signature of the shake_256() function be changed to in order to fix this error?
-
A
def shake 256(df: pd.Series) -> str:
-
B
def shake_256(df: Iterator[pd.Series]) -> Iterator[pd.Series]:
-
C
def shake 256(raw: str) -> str:
-
D
def shake_256(df: pd.Series) -> pd.Series:
Reveal answer details
Close answer details
Correct answerD
ExplanationA scalar Pandas UDF processes a batch as a pandas Series and must return a pandas Series containing one result for each input element. Its signature should therefore be def shake_256(df: pd.Series) -> pd.Series:. The original raw string signature describes a row-at-a-time Python UDF and is unsupported for this Pandas UDF form.
Question 81
Single choice
The code block shown below contains an error. The code block is intended to return a DataFrame containing all columns from DataFrame storesDF except for column sqft and column customerSatisfaction. Identify the error. Code block: storesDF.drop(sqft, customerSatisfaction)
-
A
The drop() operation only works if one column name is called at a time - there should be two calls in succession like storesDF.drop("sqft").drop("customerSatisfaction").
-
B
The drop() operation only works if column names are wrapped inside the col() function like storesDF.drop(col(sqft), col(customerSatisfaction)).
-
C
There is no drop() operation for storesDF.
-
D
The sqft and customerSatisfaction column names should be quoted like "sqft" and "customerSatisfaction".
-
E
The sqft and customerSatisfaction column names should be subset from the DataFrame storesDF like storesDF."sqft" and storesDF."customerSatisfaction".
Reveal answer details
Close answer details
Correct answerD
ExplanationIn storesDF.drop(...), string arguments identify columns by name, and more than one name may be supplied in the same call. Without quotation marks, sqft and customerSatisfaction are interpreted as Python variables rather than the requested column-name strings. Writing storesDF.drop("sqft", "customerSatisfaction") removes both columns and leaves the remaining columns in the new DataFrame.
Question 82
Single choice
Which of the following code blocks reads JSON file imports.json into a DataFrame?
-
A
spark.read().mode("json").path("/FileStore/imports.json")
-
B
spark.read.format("json").path("/FileStore/imports.json")
-
C
spark.read("json", "/FileStore/imports.json")
-
D
spark.read.json("/FileStore/imports.json")
-
E
spark.read().json("/FileStore/imports.json")
Reveal answer details
Close answer details
Correct answerD
Explanationspark.read returns the DataFrameReader, and its json method accepts the file path directly. Therefore, spark.read.json("/FileStore/imports.json") parses the JSON records and produces a DataFrame. The reader is a property, so spark.read() is not the applicable form, and path is not the terminal read operation here.
|