Sub topic 8
Columns and built-in functions
Prerequisites
This chapter assumes you can run a cell in a Databricks notebook and that you know what a DataFrame is. It also assumes you have seen spark.createDataFrame and printSchema. You should be comfortable with basic Python and with SQL expressions such as CASE WHEN.
What a Column is
A Column is an expression that Spark evaluates for every row. It is not the data. When you write F.col("amount") > 50, Spark does not compare anything yet. It builds a description of a comparison and holds it until a DataFrame uses it inside a transformation.
This is why one expression can be reused across many DataFrames, and why a Column that refers to a name that does not exist only fails when Spark analyzes the query.
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"))
is_large = F.col("amount") > 50
print(type(is_large))
print(is_large)The first print shows <class 'pyspark.sql.column.Column'>. The second shows the expression text, not any row values. Nothing has touched the data.
Ways to refer to a column
There are several equivalent ways to name a column. They differ in how they behave when names are ambiguous.
| Form | Example | Notes |
|---|---|---|
| String | `"amount"` | Accepted by many methods such as `select`, `groupBy` and `withColumn` (as the source). Short and readable. |
| `F.col` | `F.col("amount")` | Works without a DataFrame in hand. Needed to build expressions. |
| Attribute | `orders.amount` | Bound to one DataFrame. Breaks if the name has spaces or clashes with a DataFrame method. |
| Item | `orders["amount"]` | Bound to one DataFrame. Works with any name. |
A plain string is a column name only where the method expects a column. In an expression such as "amount" > 50, Python compares two literals and gives you a Python boolean. Wrap the name in F.col.
DataFrame-bound references matter after a join, when both sides have a column with the same name. orders["customer"] points to one side. A bare F.col("customer") is ambiguous and fails.
Operators on columns
Columns support arithmetic, comparison and string operators. Each returns a new Column.
expr_df = orders.select(
"order_id",
(F.col("amount") * 1.2).alias("amount_with_tax"),
(F.col("amount") >= 100).alias("is_big"),
F.col("customer").isin("alice", "bob").alias("is_known"),
F.col("customer").startswith("a").alias("starts_with_a"),
)
expr_df.show()Use &, | and ~ for logical and, or and not. Do not use Python's and, or and not. Those try to turn a Column into a single boolean and raise an error. Also put each comparison in parentheses, because & binds more tightly than >.
both = orders.filter((F.col("amount") > 50) & (F.col("customer") == "alice"))
both.show()Built-in functions
The module pyspark.sql.functions, imported by convention as F, holds several hundred functions. Each takes Columns (or names) and returns a Column. Common groups:
- Strings:
upper,lower,trim,concat,concat_ws,substring,regexp_replace,split. - Numbers:
round,floor,ceil,abs,greatest,least. - Dates and timestamps:
to_date,to_timestamp,year,month,date_add,datediff,date_trunc. - Conditionals and nulls:
when,coalesce,isnull,nullif. - Collections:
array,explode,size,struct,create_map.
shaped = orders.select(
"order_id",
F.upper("customer").alias("customer_upper"),
F.year("order_date").alias("year"),
F.date_format("order_date", "yyyy-MM").alias("year_month"),
F.coalesce("amount", F.lit(0.0)).alias("amount_filled"),
)
shaped.show()Built-in functions run inside Spark's engine. Spark can see what they do, optimize around them, and generate efficient code for them. That is the main reason to prefer them over Python functions, a point the UDF chapter returns to.
Literals with F.lit
Arguments to column functions are read as column names when they are strings. To pass a constant value, wrap it in F.lit.
tagged = orders.withColumn("source", F.lit("web"))
tagged.show()Without F.lit, withColumn("source", "web") raises an error, because "web" is not a Column. Some functions take plain Python values for arguments that are naturally constants, such as the format string in date_format or the pattern in regexp_replace. The documentation for each function states which arguments are columns.
Conditional logic with when
F.when is the DataFrame form of CASE WHEN. Chain further when calls for more branches and finish with otherwise. If you omit otherwise, unmatched rows get null.
sized = orders.withColumn(
"size",
F.when(F.col("amount") >= 100, "large")
.when(F.col("amount") >= 50, "medium")
.when(F.col("amount").isNotNull(), "small")
.otherwise("unknown"),
)
sized.show()Branches are checked in order and the first match wins. A null amount makes every comparison evaluate to null, which counts as not true, so the row falls through to the check on isNotNull and then to otherwise.
Null behavior in expressions
Most expressions return null when any input is null. null > 50 is null, not false. filter keeps only rows where the condition is true, so rows with a null amount disappear from filter(F.col("amount") > 50). They also disappear from filter(F.col("amount") <= 50). Test for nulls explicitly with isNull() and isNotNull(). Do not write == None.
orders.filter(F.col("amount").isNull()).show()How a Column expression becomes work
Expressions combine into a tree. Spark's analyzer resolves names against the schema, and the optimizer rewrites the tree. For example, it folds constants and combines filters. The result runs as part of the query plan.
The diagram below shows the path from your code to the data.
Common errors
AnalysisException: cannot resolve 'amout': a misspelled column name. The error lists the columns that do exist.ValueError: Cannot convert column into bool: you usedand,orornot, or chained a comparison such as10 < F.col("x") < 20. Use&,|,~and parentheses.AnalysisException: Reference 'customer' is ambiguous: two inputs to a join both have that column. Refer to it through the DataFrame, as inorders["customer"], or rename one side first.- Silent nulls from type mismatches: with ANSI mode off, casting text such as
"abc"to a number gives null instead of an error. CheckprintSchemaand count nulls after a cast. - Strings treated as names: passing
"web"where you meant a constant. UseF.lit("web").
Exercise
A DataFrame df has an integer column score that contains some nulls. You write df.withColumn("passed", F.when(F.col("score") >= 60, True)). What value does passed have for rows where score is null, and for rows where score is 40? Rewrite the expression so that both of those cases give False.
Show answer
Both give null, because when without otherwise returns null when no branch matches, and the comparison with a null score is null (not true). Add an otherwise: F.when(F.col("score") >= 60, True).otherwise(False). A null score then falls to otherwise and gives False, as does 40.
Exercise
Which of these lines fails, and why? (a) orders.filter("amount" > 50) (b) orders.filter(F.col("amount") > 50) (c) orders.filter((F.col("amount") > 50) and (F.col("customer") == "alice"))
Show answer
(a) and (c) fail. In (a), "amount" > 50 compares a Python string with an integer before Spark sees it, which raises a TypeError. In (c), and tries to convert a Column to a Python boolean, which raises a ValueError. Line (b) works. The fix for (c) is & with both comparisons in parentheses.