select, withColumn, filter & column expressions

Apache Spark · DataFrames

Theory

These are the everyday DataFrame transformations. select picks, renames or computes columns and returns only those; withColumn adds a new column or replaces one with the same name and keeps all the others; withColumns does several at once; filter (alias where) keeps rows whose condition is true. Conditions and calculations are column expressions built from F.col('amount'), F.lit(5) and functions in pyspark.sql.functions, combined with + - * /, comparisons, & (and), | (or) and ~ (not). In Python, wrap each comparison in parentheses because & and | bind tighter than ==.

You can also write expressions as SQL strings with F.expr('amount / qty') or selectExpr. For example, orders.filter((F.col('region') == 'North') & (F.col('amount') > 10000)).withColumn('unit_price', F.col('amount') / F.col('qty')).select('order_id', 'unit_price') returns order 101 at 55000 and order 107 at 24000. Rows where the condition is NULL are dropped, just like in SQL.

Why we use it

Nearly every pipeline is a chain of select, withColumn and filter. Column expressions run inside the JVM and are optimized by Catalyst, so they are far faster than Python UDFs or loops over collected rows.

When to use it

Use select to shape the output, withColumn or withColumns for derived columns, and filter as early as possible to cut data. Prefer built-in functions over UDFs. For many new columns, one select or withColumns is better than a long loop of withColumn calls, which bloats the plan.

How it works

  1. Start from a DataFrame
  2. filter: evaluate the condition for each row
  3. Is the condition true? Yes: Keep the row. No: Drop it (false or NULL).
  4. withColumn: compute the new column from expressions
  5. select: keep only the output columns
  6. New DataFrame (original unchanged)

Syntax

df.select("a", F.col("b").alias("b2"), (F.col("x") * 2).alias("x2"))
df.withColumn("new", expr); df.withColumns({"a": e1, "b": e2})
df.filter((F.col("a") > 1) & (F.col("b") == "x"))  # or df.where("a > 1 AND b = 'x'")
F.col, F.lit, F.expr, isin, between, like, isNull

Example

from pyspark.sql import SparkSession, functions as F

spark = (SparkSession.builder.master("local[1]")
         .config("spark.ui.enabled", "false")
         .getOrCreate())

orders = spark.createDataFrame([
    (101, 1, "North", "Laptop", 1, 55000.0, "2026-01-05"),
    (102, 2, "West",  "Phone",  2, 30000.0, "2026-01-06"),
    (103, 1, "North", "Mouse",  3,  1500.0, "2026-01-06"),
    (104, 3, "South", "Laptop", 1, 52000.0, "2026-01-07"),
    (105, 4, "West",  "Tablet", 1, 25000.0, "2026-01-08"),
    (106, 2, "East",  "Phone",  1, 15000.0, "2026-01-08"),
    (107, 5, "North", "Tablet", 2, 48000.0, "2026-01-09"),
    (108, 3, "South", "Mouse",  4,  2000.0, "2026-01-10"),
], "order_id INT, customer_id INT, region STRING, product STRING, "
   "qty INT, amount DOUBLE, order_date STRING"
).withColumn("order_date", F.to_date("order_date"))

result = (orders
          .filter((F.col("region") == "North") & (F.col("amount") > 10000))
          .withColumn("unit_price", F.col("amount") / F.col("qty"))
          .withColumns({"gst": F.round(F.col("amount") * 0.18, 2),
                        "channel": F.lit("online")})
          .select("order_id", "product", "unit_price", "gst", "channel"))
result.show()

# SQL-string expressions and helpers
orders.where("qty >= 2 AND product IN ('Phone', 'Tablet')") \
      .selectExpr("order_id", "amount / qty AS unit_price").show()
print(orders.filter(F.col("amount").between(10000, 30000)).count())

# Output:
# +--------+-------+----------+------+-------+
# |order_id|product|unit_price|   gst|channel|
# +--------+-------+----------+------+-------+
# |     101| Laptop|   55000.0|9900.0| online|
# |     107| Tablet|   24000.0|8640.0| online|
# +--------+-------+----------+------+-------+
#
# +--------+----------+
# |order_id|unit_price|
# +--------+----------+
# |     102|   15000.0|
# |     107|   24000.0|
# +--------+----------+
#
# 3

Key points

Apache Spark topics

Spark Fundamentals

Spark Architecture

RDDs

DataFrames

Aggregations & Joins

Spark SQL

Window Functions

Cleaning & Complex Types

UDFs

Performance Tuning

Structured Streaming

MLlib & Ecosystem

Interview Prep

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Master Apache Spark

PySpark and Spark SQL from the ground up: DataFrames, joins, window functions, partitions and performance tuning, Structured Streaming and more. Click any topic in the sidebar to open it right here.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice PySpark Write real PySpark — DataFrames, joins, window functions and Spark SQL — in a live editor with hidden tests and instant checking. Start practising →
Section {{ sec.num }}

{{ sec.label }}

Spark  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

{{ sec.h }}

{{ sec.body }}

{{ sec.body }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
On screen — where to click

{{ rich.ui.title }}

{{ u.text }}
  1. {{ st.n }}{{ st.text }}
{{ rich.ui.title }}
{{ u.text }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
Want to run this yourself? Try the same API on Practice PySpark Online right in your browser, or run it locally after pip install pyspark (needs Java 17+), or paste it into a Databricks Free Edition notebook.
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic