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
- Start from a DataFrame
- filter: evaluate the condition for each row
- Is the condition true? Yes: Keep the row. No: Drop it (false or NULL).
- withColumn: compute the new column from expressions
- select: keep only the output columns
- 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, isNullExample
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
- select returns only the listed columns; withColumn keeps all and adds or replaces one
- filter and where are the same; both accept a Column or a SQL string
- Use & | ~ with parentheses around each comparison, not Python and/or/not
- F.lit() wraps a constant; F.expr() and selectExpr() accept SQL expressions
- Many withColumn calls in a loop bloat the plan; use withColumns or one select