Sub topic 9
Selecting and filtering rows
This chapter assumes you can run a cell in a Databricks notebook, know that spark is already defined, and have seen a DataFrame with a schema. It uses the orders DataFrame from earlier chapters, with order_id, customer, order_date and amount columns.
Selecting columns
select returns a new DataFrame that contains only the columns you name. You can pass column names as strings or as column expressions.
from pyspark.sql import functions as F
orders = spark.createDataFrame(
[
(1, "alice", "2024-01-05", 120.0),
(2, "bob", "2024-01-06", 75.5),
(3, "alice", "2024-02-10", 30.0),
(4, "carol", "2024-02-11", None),
],
"order_id INT, customer STRING, order_date STRING, amount DOUBLE",
)
orders = orders.withColumn("order_date", F.to_date("order_date"))
orders.select("order_id", "customer").show()
orders.select(F.col("amount") * 2, F.upper("customer")).show()The second call shows that select can compute values, not only pick columns. Use alias to give a computed column a readable name.
Filtering rows
filter keeps the rows where a condition is true. where is an alias with identical behavior. The condition is a column expression that evaluates to a boolean.
big_orders = (
orders
.filter(F.col("amount") > 50)
.select("order_id", "customer", "amount")
.withColumn("amount_rounded", F.round("amount"))
)
big_orders.show()Both filter and select are lazy transformations. Nothing runs until show() is called.
Combining conditions
Use & for and, | for or, and ~ for not. Wrap each comparison in parentheses, because these operators bind more tightly than comparisons in Python.
orders.filter(
(F.col("customer") == "alice") & (F.col("amount") >= 100)
).show()
orders.filter(F.col("customer").isin("bob", "carol")).show()
orders.filter(F.col("order_date").between("2024-02-01", "2024-02-29")).show()Nulls in filters
A comparison with null produces null, not false, and filter drops rows where the condition is not true. In the sample data, carol's amount is null, so both amount > 50 and amount <= 50 exclude her. Test for nulls explicitly.
orders.filter(F.col("amount").isNull()).show()
orders.filter(F.col("amount").isNotNull() & (F.col("amount") <= 50)).show()Filter early
Spark's optimizer often pushes filters down toward the data source, so rows are discarded before expensive steps such as joins. Writing filter early in the chain still makes your intent clear and keeps the data small.
Common errors
| Symptom | Cause | Fix | Column |
|---|---|---|---|
| `ValueError: Cannot convert column into bool` | Used `and`, `or` or `not` | Use `&`, `\ | ` and `~` |
| Wrong rows or a parse error | Missing parentheses around comparisons | Parenthesize each condition | |
| Null rows disappear | Comparison with null is not true | Use `isNull` or `isNotNull` | |
| `AnalysisException: cannot resolve column` | Misspelled column name | Check `printSchema()` |
Exercise
Write a filter that keeps orders from alice or bob with an amount of at least 50, and explain why carol's order is excluded either way.
Show answer
orders.filter(F.col("customer").isin("alice", "bob") & (F.col("amount") >= 50)). Carol is excluded because her customer is not in the list. Her null amount would also make the comparison null, which filter treats as not true.