Sub topic 8
Columns and built-in functions
This chapter assumes you can run a cell in a Databricks notebook, that spark is already available, and that you know what a DataFrame is. You should also be comfortable with basic Python or SQL.
What a Column is
A Column is an expression that Spark evaluates for every row. It is not a stored list of values. When you write F.col("amount") > 50, nothing is computed yet. You get a description of a computation, and Spark runs it later when an action needs the result.
The built-in functions live in pyspark.sql.functions. By convention it is imported as F.
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",
)
expr = F.col("amount") * 1.2
print(type(expr))The output shows a Column object, not numbers. This is why the expression can be passed around, stored in a variable, and combined with others.
Ways to refer to a column
Several forms point to the same column:
| Form | Example | Notes |
|---|---|---|
| String name | `"amount"` | Accepted by many methods, such as `select` and `groupBy`. |
| `F.col` | `F.col("amount")` | Works anywhere a Column is needed. Does not depend on a specific DataFrame. |
| Attribute | `orders.amount` | Ties the column to one DataFrame. Fails for names with spaces or that clash with a DataFrame method. |
| Bracket | `orders["amount"]` | Like the attribute form, but works for any name. |
Prefer F.col for most code. It is short and works in chained expressions. Use the bracket form when you must tell apart columns of the same name after a join.
Building expressions
Columns support arithmetic, comparison and boolean operators. Combine conditions with &, | and ~, and put parentheses around each comparison. Python's and, or and not do not work on Columns.
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",
)
result = orders.select(
"order_id",
F.upper("customer").alias("customer_upper"),
F.to_date("order_date").alias("order_date"),
(F.col("amount") * 1.2).alias("amount_with_tax"),
((F.col("amount") > 50) & (F.col("customer") != "bob")).alias("flag"),
)
result.show()Each expression becomes one output column. alias names the result. Without it, Spark generates a name such as (amount * 1.2).
Common built-in functions
Built-in functions run inside Spark's engine, which can optimize them. Learn the main groups first:
- Strings:
upper,lower,trim,concat,substring,regexp_replace - Dates:
to_date,date_add,datediff,year,month - Math:
round,abs,floor - Conditional:
when,otherwise,coalesce
Use F.when for if/else logic, and F.lit to turn a plain Python value into a Column.
labeled = orders.select(
"order_id",
F.when(F.col("amount") >= 100, "large")
.when(F.col("amount") >= 50, "medium")
.otherwise("small")
.alias("size"),
F.coalesce(F.col("amount"), F.lit(0.0)).alias("amount_or_zero"),
)
labeled.show()Order 4 has a null amount. Both comparisons evaluate to null, so when does not match and the row falls to otherwise, giving "small". Handle nulls explicitly when that is not what you want.
Common errors
- Writing
df.amount > 50 and df.customer == "alice"raises an error about converting a Column to bool. Use&with parentheses. - Passing a plain string where a literal is needed, such as
F.coalesce("amount", 0), can fail or misread the string as a column name. Wrap constants inF.lit. - Using Python's built-in
roundorsumon a Column instead ofF.roundorF.sumgives the wrong behavior or an error.
Exercise
Write a select that returns orderid and a column named isbig that is true when amount is greater than 50 and the customer is "alice". Why must each comparison be in parentheses?
Show answer
orders.select("orderid", ((F.col("amount") > 50) & (F.col("customer") == "alice")).alias("isbig")). The & operator has higher precedence than comparison operators in Python, so without parentheses Python would evaluate 50 & F.col("customer") first and raise an error.