Sub topic 2
Reading Files and Tables
Assume you know basic Python or SQL, understand rows and columns, and can attach a Databricks notebook to compute. This chapter uses the preconfigured spark session and PySpark DataFrames.
Read data with a schema
A DataFrame is a distributed table with named columns and data types. Give Spark a schema when reading files so values do not depend on type inference.
from pyspark.sql import functions as F
orders = (
spark.read
.format("csv")
.option("header", True)
.schema("order_id INT, customer STRING, order_date DATE, amount DOUBLE")
.load("/Volumes/main/default/raw/orders.csv")
)
orders.printSchema()
display(orders)The path is an example. Replace it with a path that your workspace can read. You can also read a table:
orders = spark.table("main.default.orders")printSchema() shows the column names, types, and whether values can be null. display() gives a notebook-friendly preview.
Columns and built-in functions
A PySpark column is an expression, not a single value. Built-in functions create expressions that Spark can optimize.
clean_orders = (
orders
.withColumn("order_year", F.year("order_date"))
.withColumn("amount_rounded", F.round("amount", 2))
.select("order_id", "customer", "order_year", "amount_rounded")
.filter(F.col("amount_rounded") > 50)
)
display(clean_orders)select() chooses or computes columns. filter() keeps rows whose condition is true. withColumn() adds a column or replaces an existing column.
Nulls and duplicates
A null means a value is missing or unknown. Comparisons with null do not evaluate to true, so a filter may exclude those rows.
usable = orders.filter(F.col("amount").isNotNull())
filled = orders.fillna({"amount": 0.0})
unique_orders = orders.dropDuplicates(["order_id"])Use fillna() only when the replacement has a valid meaning. Use dropna() when incomplete rows cannot be used.
Exercise
How do you keep orders with a non-null amount and create a column containing the month?
Show answer
Use orders.filter(F.col("amount").isNotNull()).withColumn("order_month", F.month("order_date")).