Spark DataFrame Operations

DataFrame operations reshape, filter, and summarize tables of data. Each operation returns a new DataFrame and leaves the original untouched. Spark records the steps and runs them only when you ask for a result. Mastering a small set of operations covers most daily data work.

Sample Data

Every example below uses a small employee table.

data = [
    ("Asha",  "Sales",  52000, 29),
    ("Ben",   "Sales",  48000, 35),
    ("Chitra","IT",     75000, 41),
    ("Dev",   "IT",     68000, 26),
    ("Elena", "HR",     45000, 38),
]
df = spark.createDataFrame(data, ["name", "dept", "salary", "age"])

Picking Columns with select

The select operation keeps only the columns you name. Fewer columns mean less data in memory and on the network.

df.select("name", "salary").show()
df.select(df.name, (df.salary * 1.1).alias("new_salary")).show()

Filtering Rows

The filter operation keeps rows that satisfy a condition. The where operation is an exact alias.

df.filter(df.salary > 50000).show()
df.filter((df.dept == "IT") & (df.age < 30)).show()
df.where("dept = 'HR'").show()

Wrap each condition in parentheses when you combine them. Use & for AND, | for OR, and ~ for NOT.

Adding, Renaming, and Dropping Columns

from pyspark.sql.functions import col

df2 = (df.withColumn("bonus", col("salary") * 0.10)
         .withColumnRenamed("dept", "department")
         .drop("age"))
df2.show()

Grouping and Aggregating

The groupBy operation splits rows into buckets by a column. The agg operation then calculates one summary per bucket.

from pyspark.sql.functions import avg, max, count

df.groupBy("dept").agg(
    count("*").alias("people"),
    avg("salary").alias("avg_salary"),
    max("age").alias("oldest")
).show()
Original rows                 groupBy("dept")            agg(...)

Asha   Sales 52000            Sales : Asha, Ben          Sales  2  50000
Ben    Sales 48000            IT    : Chitra, Dev        IT     2  71500
Chitra IT    75000     --->   HR    : Elena        ---> HR     1  45000
Dev    IT    68000
Elena  HR    45000

Sorting, Limiting, and Removing Duplicates

df.orderBy(col("salary").desc()).show()
df.orderBy("dept", col("age").desc()).limit(3).show()
df.select("dept").distinct().show()
df.dropDuplicates(["dept"]).show()

Chaining Operations

Operations chain together into a readable pipeline. Each step feeds the next.

result = (df.filter(col("age") > 25)
            .groupBy("dept")
            .agg(avg("salary").alias("avg_salary"))
            .orderBy(col("avg_salary").desc()))
result.show()
df --> filter --> groupBy --> agg --> orderBy --> show
                                           |
                                  Spark runs all steps here

Transformations and Actions

  • Transformations such as select, filter, withColumn, groupBy, and orderBy build a plan.
  • Actions such as show, count, collect, and write run the plan.

Call explain() on any DataFrame to read the plan Spark prepared.

Habits That Save Time

  • Filter early so later steps handle fewer rows.
  • Select only the needed columns before heavy operations.
  • Prefer column expressions over Python loops. Spark optimizes expressions and cannot optimize loops.
  • Use show(5) during development instead of collect().

Quick Reference

TaskOperationExample
Keep some columnsselectdf.select("name")
Keep some rowsfilterdf.filter(df.age > 30)
Add a columnwithColumndf.withColumn("x", col("a") + 1)
Summarize groupsgroupBy and aggdf.groupBy("dept").count()
Order rowsorderBydf.orderBy("age")
Remove repeatsdropDuplicatesdf.dropDuplicates(["name"])

Common Mistakes

Forgetting to Capture the Result

DataFrames never change in place. A line such as df.withColumn("bonus", col("salary") * 0.1) creates a new DataFrame and throws it away. Assign the result to a variable or chain it into the next step.

Mixing Python and Column Operators

Python keywords and, or, and not do not work on columns. Use &, |, and ~ with parentheses around each condition. A missing bracket produces a confusing error message.

Collecting Too Much Data

The collect action pulls every row into the driver program. A large table can crash the driver. Use show, take, limit, or write the result to storage instead.