Derived Columns
Part of the Fundamentals section of Coddy's PySpark journey. Lesson 6 of 18.
Use withColumn(name, expression) to add a computed column. If the name already exists, the returned DataFrame replaces that column. An expression is evaluated for each row.
priced = items.withColumn("double_price", F.col("price") * 2)This retains the existing columns and adds double_price. Use F.lit(value) when you need a constant column rather than a column reference.
Challenge
EasyAdd value equal to price * quantity. Keep the original columns, followed by value.
Write transform(df) and return a Spark DataFrame. The checker supplies df with schema item string, price int, quantity int. The session and F (PySpark functions) are already available. Do not print; the checker displays the returned rows. Return columns in this order: item, price, quantity, value.
Try it yourself
def transform(df):
return df
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
2Transforming Data
Select ColumnsFilter RowsDerived ColumnsSort RowsMissing ValuesRecap: Stock ReportPractice on your own: Online Python compiler