Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 22

DataFrame Transformations and Actions

This lesson is built with resources from blog.devgenius.io and blog.dataengineerthings.org.

Hello! Welcome back to our hands-on exploration of Apache Spark.

In our last session, we learned how to get data into a Spark DataFrame from various sources. Now that we can load our data, the next logical step is to learn how to manipulate it. This is the core of most data engineering and analytics workloads.

Today, your goal is to apply common transformations (e.g., selecting, filtering) and actions (e.g., aggregations) to DataFrames. These operations are the fundamental verbs you'll use to clean, reshape, and analyze data at scale. As a software architect, you can think of this as learning the core methods of the primary API for distributed data processing.

The Core Idea: Transformations and Actions

A crucial concept in Spark is the distinction between transformations and actions. Understanding this is key to writing efficient Spark code.

  • Transformations are operations that create a new DataFrame from an existing one. They are lazy, meaning Spark doesn't execute them immediately. Instead, it builds up a plan of computation, much like an architect drafts a full blueprint before construction begins. Examples include selecting columns or filtering rows.
  • Actions are operations that trigger the execution of all the planned transformations. An action is what tells Spark, "Okay, run the plan now and give me a result." This could be displaying data on the screen, counting rows, or saving the output to a file.

To get a formal definition and see a list of examples, please read the introductory section of this article.

Demystifying PySpark: A Comprehensive Guide to DataFrame Transformations and Actions

The article "Demystifying PySpark" provides a clear and concise explanation of the difference between transformations and actions.

Read the section titled "Understanding Transformations and Actions in PySpark" to solidify the definitions of these two types of operations.

Narrow vs. Wide Transformations

For you as an architect, it's useful to know that transformations can be further categorized. This distinction has significant performance implications.

  • Narrow Transformations: Each partition of the output DataFrame depends on only one partition of the input DataFrame. Examples include select and filter. These are efficient as they don't require shuffling data across the cluster.
  • Wide Transformations: Each partition of the output DataFrame may depend on data from many partitions of the input DataFrame. This requires a shuffle, where Spark moves data between executor nodes. Examples include groupBy and join. Shuffles are expensive operations, and minimizing them is a key aspect of Spark performance tuning.

A Practical Guide to Common Transformations

Let's walk through the most essential transformations. These are your bread-and-butter operations for data manipulation. Many of these will feel familiar, given your experience with SQL.

We'll use a hypothetical DataFrame df loaded with employee data containing columns like name, department, salary, and age.

The following resource provides excellent code examples for these operations. We will refer to it as we discuss each transformation.

Demystifying PySpark: A Comprehensive Guide to DataFrame Transformations and Actions

This article contains practical code snippets for the most common DataFrame transformations. We'll be discussing the first four in detail.

Scan through the examples under the "Common Transformations with Examples" section. We'll focus on select, filter, withColumn, and groupBy. You don't need to read about join, orderBy, or distinct yet; we will cover those later.

1. Selecting Columns (select)

This is equivalent to the SELECT clause in SQL. You use it to choose the columns you want to keep.

# Select just the name and salary columns
df_selected = df.select("name", "salary")

This is a narrow transformation.

2. Filtering Rows (filter or where)

This is equivalent to the WHERE clause in SQL. It allows you to select a subset of rows based on a condition.

# Keep only employees who make more than 60000
df_filtered = df.filter(df.salary > 60000)

# You can also use the 'where' alias, which might feel more natural
df_filtered_alt = df.where("salary > 60000")

This is also a narrow transformation.

3. Adding or Replacing Columns (withColumn)

This is used to create a new column or update an existing one, often based on the values of other columns.

# Create a new 'bonus' column calculated as 10% of salary
df_with_bonus = df.withColumn("bonus", df.salary * 0.1)

# Overwrite the 'salary' column with an increased value
df_updated_salary = df.withColumn("salary", df.salary * 1.05)

This is a narrow transformation.

4. Grouping and Aggregating (groupBy and agg)

This is equivalent to the GROUP BY clause in SQL, used with aggregate functions like AVG, SUM, and COUNT. This is the classic example of a wide transformation because Spark must shuffle data to bring all rows for a given group key together on the same executor.

# Import the avg function
from pyspark.sql.functions import avg, sum, count

# Group by department and calculate the average salary for each
df_grouped = df.groupBy("department").agg(avg("salary").alias("avg_salary"))

The .agg() method takes one or more aggregate functions. Using .alias() is good practice for renaming the resulting column to something meaningful.


Triggering Execution with Actions

After defining our chain of transformations, we need an action to see a result.

The most common actions are:

  • show(): Displays the first N rows of the DataFrame (default is 20). This is the most common way to inspect results during development.
  • count(): Returns the total number of rows in the DataFrame.
  • collect(): Returns all the data in the DataFrame as a list of Row objects to the driver program. Use this with extreme caution! If the DataFrame is large, it can easily exhaust the memory of the driver node and crash your application. It is only safe for very small, filtered-down datasets.

Let's see how an action triggers our plan. The operations are chained together in a fluent API style that should be familiar from other programming contexts.

from pyspark.sql.functions import avg

# A complete chain: transformation -> transformation -> action
df.filter(df.salary > 60000) \
  .groupBy("department") \
  .agg(avg("salary").alias("avg_salary_for_high_earners")) \
  .show()

When show() is called, Spark's Catalyst Optimizer analyzes this entire chain, creates an efficient physical execution plan (minimizing shuffles where possible), and runs the job across the cluster.

Test your understanding!

You have a DataFrame named sales_df with the columns product_id, category (e.g., "Electronics", "Books"), units_sold, and revenue.

Write a single chain of PySpark code to find the total revenue for each category, but only including sales from the "Electronics" category where more than 10 units were sold. Display the final result.

Show answer
from pyspark.sql.functions import sum

# Assume sales_df is already created

sales_df.filter((sales_df.category == "Electronics") & (sales_df.units_sold > 10)) \
        .groupBy("category") \
        .agg(sum("revenue").alias("total_revenue")) \
        .show()

# Expected output would look something like this:
# +-----------+-------------+
# |   category|total_revenue|
# +-----------+-------------+
# |Electronics|    125000.75|
# +-----------+-------------+

This code first filters the data down to the relevant rows (a narrow transformation), then groups by category and aggregates the revenue (a wide transformation), and finally, the show() action triggers the computation and displays the result.


Conclusion

In this lesson, you've learned the fundamental mechanics of data manipulation in Spark. You now understand the critical difference between lazy transformations and eager actions, and you can perform the most common operations to select, filter, and aggregate your data.

Key Takeaways:

  • Transformations (select, filter, groupBy) are lazy operations that build a plan.
  • Actions (show, count, collect) are eager operations that trigger the execution of that plan.
  • Transformations can be narrow (efficient, no shuffle) or wide (expensive, requires a shuffle). groupBy is a classic wide transformation.
  • Operations can be chained together to express complex logic, which Spark's optimizer then converts into an efficient execution plan.
  • Always be careful with collect(), as it can overload your driver node.

You've now learned how to load data and how to perform basic manipulations on a single DataFrame. In our next lesson, we will tackle another essential wide transformation: performing joins between large datasets using Spark DataFrames. This will enable you to combine and enrich data from multiple sources, a critical skill for any data architect.