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 met F.col and the built-in functions in pyspark.sql.functions. You should also know that DataFrames are lazy. Here you will pick columns with select, keep rows with filter, and learn the edge cases that cause wrong results.
The sample data
The examples use the orders DataFrame from earlier chapters. Run this cell first so every later cell works on its own.
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.printSchema()Carol's amount is null. That row matters in the filtering section below.
Selecting columns
select returns a new DataFrame that contains only the columns you list. It never changes the original. You can name columns in several ways.
orders.select("order_id", "customer").show()
orders.select(F.col("order_id"), F.col("amount") * 2).show()
orders.select(orders["customer"], orders.amount).show()The three forms behave the same for simple cases. Strings are the shortest. F.col("name") works anywhere a column is expected and does not need a DataFrame variable. orders["name"] and orders.name tie the column to one specific DataFrame. That helps after a join, when two DataFrames share a column name.
Attribute access (orders.amount) fails when a column name contains a space or matches a DataFrame method name. Prefer F.col or bracket access in those cases.
Expressions, aliases and star
A select can compute new values. Use alias to name the result, because otherwise Spark generates a name like (amount * 2).
orders.select(
"order_id",
(F.col("amount") * 1.1).alias("amount_with_tax"),
F.upper("customer").alias("customer_upper"),
).show()
orders.select("*", F.lit("web").alias("channel")).show()"*" expands to every column, so select("*", ...) is the usual way to keep everything and add one more. F.lit wraps a constant as a column.
Related ways to choose columns
| Goal | Code | Note |
|---|---|---|
| Drop columns | `orders.drop("amount")` | Silently ignores names that do not exist |
| Rename one column | `orders.withColumnRenamed("amount", "total")` | No error if the old name is missing |
| Select with SQL text | `orders.selectExpr("amount * 2 AS double_amount")` | Takes SQL expression strings |
| Select by pattern | `orders.select([c for c in orders.columns if c.startswith("order")])` | `columns` is a plain Python list |
drop and withColumnRenamed do nothing when the name is wrong. A typo there produces no error, so check the schema afterwards.
Filtering rows
filter keeps the rows for which a condition is true. where is an alias with identical behavior, so use whichever your team prefers.
orders.filter(F.col("amount") > 50).show()
orders.where("amount > 50").show()You can pass either a Column expression or a SQL string. Column expressions are checked as you build them and work well with editor tooling. SQL strings are compact and handy for quick exploration.
Combining conditions
Python's and, or and not do not work on columns. Use &, | and ~, and put each comparison in parentheses. The parentheses matter because & binds more tightly than > in Python.
orders.filter((F.col("amount") > 50) & (F.col("customer") == "alice")).show()
orders.filter((F.col("customer") == "bob") | (F.col("amount") < 50)).show()
orders.filter(~(F.col("customer") == "alice")).show()Without the parentheses, Python reads F.col("amount") > 50 & F.col("customer") == "alice" in the wrong order, and Spark raises an error about converting a column to a boolean.
Membership, ranges and text
orders.filter(F.col("customer").isin("alice", "carol")).show()
orders.filter(F.col("amount").between(50, 100)).show()
orders.filter(F.col("customer").startswith("a")).show()
orders.filter(F.col("customer").like("%o%")).show()
orders.filter(F.col("order_date") >= "2024-02-01").show()between is inclusive at both ends. Comparing a date column with an ISO string such as "2024-02-01" works because Spark casts the string to a date. This is convenient, but an explicit F.lit("2024-02-01").cast("date") makes the intent clear.
Nulls in filters
SQL uses three-valued logic: a comparison can be true, false or unknown. A comparison with null gives unknown, and filter keeps only rows where the condition is true. Rows where it is unknown are dropped.
orders.filter(F.col("amount") > 50).count() # 2
orders.filter(F.col("amount") <= 50).count() # 1The two counts add up to 3, but the table has 4 rows. Carol's row appears in neither result, because null > 50 and null <= 50 are both unknown. The same applies to !=. A filter amount != 30 also loses Carol.
To test for null, use dedicated methods:
orders.filter(F.col("amount").isNull()).show()
orders.filter(F.col("amount").isNotNull()).show()
orders.filter(F.col("amount").isNull() | (F.col("amount") <= 50)).show()Writing F.col("amount") == None returns unknown for every row, so it matches nothing. Use isNull. When you need a null-safe comparison between two columns, use eqNullSafe.
orders.filter(F.col("amount").eqNullSafe(None)).show()Filtering is lazy and can be pushed down
select and filter are transformations. Nothing runs until an action such as show, count or a write. The Catalyst optimizer (Spark's query planner) also reorders work. When you read from Parquet or Delta, it can push filters down so the data source skips files or row groups that cannot match. It can also prune columns, so only the columns you select are read from storage.
You can check this with explain:
orders.filter(F.col("amount") > 50).select("order_id").explain()For a file or table source, look for PushedFilters and a narrow ReadSchema in the scan node. Because the optimizer does this for you, you do not need to filter early in your code to get the benefit. Write the query in the clearest order.
Filters on a computed column or a UDF often cannot be pushed down. Filtering on the raw column, for example order_date >= "2024-02-01" instead of a function applied to order_date, gives the planner the best chance.
Limiting and sampling
limit(n) returns a DataFrame with at most n rows. show(n) only prints rows. Neither promises a particular order unless you sort first.
orders.orderBy(F.col("amount").desc_nulls_last()).limit(2).show()desc_nulls_last makes the null placement explicit. By default, nulls sort first in ascending order and last in descending order.
Common mistakes
- Using
and,orornotinstead of&,|and~. - Omitting parentheses around each comparison.
- Using
== Noneinstead ofisNull(). - Expecting
!=or<=to keep null rows. - Assuming
limitreturns the "first" rows without a sort. - Reusing a variable name such as
ordersfor the filtered result and then forgetting that the original is gone from the notebook's state. Give filtered results their own names.
Exercise
Using the orders DataFrame, write a filter that returns every order whose amount is not 120.0, including orders where the amount is missing. Which order_ids should it return?
Show answer
Use orders.filter((F.col("amount") != 120.0) | F.col("amount").isNull()). It returns order_ids 2, 3 and 4. The plain filter amount != 120.0 would return only 2 and 3, because the comparison with null for order 4 is unknown. Adding isNull() keeps it.
Exercise
This code fails: orders.filter(F.col("amount") > 50 & F.col("customer") == "bob"). Why, and how do you fix it?
Show answer
& binds more tightly than > and == in Python, so the expression combines 50 & F.col("customer") first, which Spark cannot evaluate as a boolean. Put parentheses around each comparison: orders.filter((F.col("amount") > 50) & (F.col("customer") == "bob")).