Spark & PySpark
Essential RDD Transformations & Actions in PySpark (Hands-on Guide)
Introduction
Introduction
Apache Spark’s Resilient Distributed Datasets (RDDs) are the backbone of distributed data processing.
In our previous blog, we explored what RDDs are and how they work under the hood.
But theory alone isn’t enough. To truly unlock the power of Spark, you need to understand and practice RDD operations — the transformations and actions that turn raw data into insights.
In this hands-on guide, we’ll cover:
- What transformations & actions are.
- The difference between them (lazy vs eager).
- Commonly used operations in PySpark (with code examples).
- A mini-project (word count).
By the end, you’ll be ready to write Spark jobs confidently.
Transformations vs Actions
In Spark:
- Transformations → create a new RDD from an existing one (lazy).
- Actions → trigger execution and return a result (eager).
👉 Think of transformations as “setting up a plan” and actions as “executing the plan.”
Quick Reference Cheat Sheet
Here’s a handy table to keep in mind:
Transformations

Actions

💡 Pro Tip: Avoid using collect() on very large RDDs — it can overwhelm the driver. Use take() or write to storage instead.
Now we will see how transformations are used:
Common Transformations in PySpark
1. map()
Applies a function to each element.
rdd = sc.parallelize([1, 2, 3, 4, 5])
mapped = rdd.map(lambda x: x * 2)
print(mapped.collect()) # [2, 4, 6, 8, 10]2. filter()
Keeps only elements satisfying a condition.
filtered = rdd.filter(lambda x: x % 2 == 0)
print(filtered.collect()) # [2, 4]3. flatMap()
Like map(), but flattens results (useful for splitting text).
lines = sc.parallelize(["hello world", "big data spark"])
words = lines.flatMap(lambda line: line.split(" "))
print(words.collect())
# ['hello', 'world', 'big', 'data', 'spark']4. reduceByKey()
Aggregates values with the same key.
pairs = sc.parallelize([("a", 1), ("b", 1), ("a", 2)])
reduced = pairs.reduceByKey(lambda x, y: x + y)
print(reduced.collect())
# [('b', 1), ('a', 3)]5. distinct()
Removes duplicate elements.
numbers = sc.parallelize([1, 2, 2, 3, 3, 3])
print(numbers.distinct().collect()) # [1, 2, 3]Common Actions in PySpark
1. collect()
Returns all elements to the driver. ⚠️ Use with caution for large datasets.
print(mapped.collect())
# [2, 4, 6, 8, 10]2. count()
Returns the number of elements.
print(rdd.count()) # 53. take(n)
Returns the first n elements.
print(rdd.take(3)) # [1, 2, 3]4. first()
Returns the first element.
print(rdd.first()) # 15. saveAsTextFile()
Writes RDD to storage.
words.saveAsTextFile("output/words")Mini Project: Word Count with PySpark RDDs
The classic word count problem demonstrates transformations + actions working together.
text = sc.textFile("sample.txt")
counts = (text.flatMap(lambda line: line.split(" "))
.map(lambda word: (word, 1))
.reduceByKey(lambda x, y: x + y))
print(counts.collect())- flatMap → split lines into words.
- map → map each word to
(word, 1). - reduceByKey → aggregate word counts.
- collect → trigger execution & fetch results.
flatMapis used instead ofmapbecausemapwould return a list of lists.flatMapflattens the nested lists so you get one list of words.
Real-World Tie-In: Counting Active Users
Let’s see how this works with a realistic log dataset. Suppose we have a file of server logs where the user ID is the third column.
logs = sc.textFile("server_logs.txt")
user_activity = (
logs.map(lambda line: (line.split()[2], 1)) # user_id at index 2
.reduceByKey(lambda x, y: x + y) # count per user
.sortBy(lambda x: -x[1]) # sort by activity
)
print("Top 5 active users:", user_activity.take(5))👉 In practice, this can help identify power users, spammers, or unusual patterns in logs at scale.
Lazy Evaluation & DAGs (Quick Recap)
Transformations in Spark are lazy → they don’t run immediately. Instead, Spark builds a DAG (Directed Acyclic Graph) of operations.
Execution only happens when an action is called.
Example
data = sc.parallelize([1, 2, 3, 4, 5])
result = data.filter(lambda x: x % 2 == 0).map(lambda x: x * 10)
print(result.collect())Here, Spark waits until .collect() before executing the filter + map steps.
Transformations vs Actions: A Visual
RDD → map() → filter() → reduceByKey() --(Action: collect)--> ResultsSpark builds this chain as a Directed Acyclic Graph (DAG) and only executes when an action (like collect()) is called.
Advanced Tips:
Cache / Persist RDDs: If you reuse an RDD multiple times (e.g., in multiple actions), use rdd.cache() to avoid recomputation.Partitioning Matters: Large RDDs can be split into multiple partitions for parallel processing. Use rdd.repartition(n) to optimize performance.Avoid collect() on huge datasets: Instead, use take(n) or write to storage. Collecting large datasets may crash the driver.Use reduceByKey wisely: It performs a map-side combine, reducing shuffle data, making it faster than groupByKey.
🧠 Explanation:
The image above illustrates the difference between executing operations without caching and with caching in Apache Spark.
- Without Spark Caching:
Every iteration (e.g.,iter.1,iter.2,iter.3) reads the input data from the source repeatedly. This means for each action or transformation chain, Spark reprocesses the entire dataset, leading to redundant computation and slower execution — especially when working with large RDDs or iterative algorithms like machine learning. - With Spark Caching:
Spark reads the input data only once and stores the intermediate RDD in distributed memory (cache). Subsequent transformations and actions reuse this cached data directly, avoiding repeated reads and computations.
This caching mechanism drastically improves performance for workloads where the same dataset is accessed multiple times.
In short, caching allows Spark to perform one-time data loading followed by fast, memory-based transformations, making it a critical optimization for iterative processing.
Conclusion
Mastering RDD transformations and actions in PySpark is the first step toward becoming a strong data engineer.
They are the foundation of ETL pipelines, log analysis, machine learning preprocessing, and real-time jobs.
While DataFrames and SQL APIs often take the spotlight today, RDDs are still critical for fine-grained control, working with unstructured data, and understanding Spark’s internals.
👉 Coming Next: PySpark vs Pandas — When to Use What in Data Engineering