DP-600 · Question #98
Drag and Drop Question You are building a solution by using a Fabric notebook. You have a Spark DataFrame assigned to a variable named df. The DataFrame returns four columns. You need to change the…
The correct answer is withColumn; col; cast. This question tests knowledge of PySpark DataFrame API methods for modifying column data types while preserving all existing columns in a Fabric notebook environment.
Question
Drag and Drop Question You are building a solution by using a Fabric notebook. You have a Spark DataFrame assigned to a variable named df. The DataFrame returns four columns. You need to change the data type of a string column named Age to integer. The solution must return a DataFrame that includes all the columns. How should you complete the code? To answer, drag the appropriate values to the correct targets. Each value may be used once, more than once, or not at all. You may need to drag the split bar between panes or scroll to view content. NOTE: Each correct selection is worth one point. Answer:
Answer Area
Drag items
Correct arrangement
- withColumn
- col
- cast
Explanation
This question tests knowledge of PySpark DataFrame API methods for modifying column data types while preserving all existing columns in a Fabric notebook environment.
Approach. The correct code is: df = df.withColumn('Age', col('Age').cast('integer')). withColumn is used to add or replace a column in a DataFrame while keeping all other columns intact - it returns a new DataFrame with the specified column updated. col('Age') references the existing 'Age' column by name as a Column object, and .cast('integer') converts its data type to integer. This three-part combination is the idiomatic PySpark pattern for in-place column type conversion without losing any other columns.
Concept tested. PySpark DataFrame column transformation using withColumn + col + cast to change a column's data type while preserving all other columns in the DataFrame
Topics
Community Discussion
No community discussion yet for this question.