Databricks Certified Associate Developer For Apache Spark 30 · Free Practice Question Medium

Question 15

Which of the following operations can be used to create a new DataFrame with a new column and all previously existing columns from an existing DataFrame ?
  • A DataFrame.drop()
  • B DataFrame.withColumn()
  • C DataFrame.withColumnRenamed()
  • D DdataFrame.head()
  • E DataFrame.filter()
Reveal correct answer

Correct answer: B

Explanation

withColumn() method of the DataFrame class is used to add a new column to a DataFrame or to replace the value of an existing column. It takes two arguments: the name of the new column and the value to be placed in the column. The value can be a literal value, a column reference, or a function that generates a value for each row.

For example, consider the following DataFrame df:

To add a new column age with a constant value of 25 for all rows, you can use the following code:

This will produce the following DataFrame:

To add a new column price that is calculated based on the value of the id column, you can use the following code:

This will produce the following DataFrame:

To replace the value of an existing column, you can use the same syntax as above and specify the name of the existing column as the first argument. For example, to replace the values of the name column with the lowercase version of the values, you can use the following code:

Discussion

Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.

You must be logged in to post a comment.

Preparing For

Your Certification?

255+ certifications
Detailed explanations
Free PDF samples

Has All The Questions You Need