Skip to content
TeachTrails
Data EngineeringPySpark

PySpark Tutorial for Beginners: Install, SparkSession and Your First DataFrame

Learn PySpark from zero: what Spark is, installing PySpark on your laptop, SparkSession, your first DataFrame, lazy evaluation, explain() and a real Spark 4 gotcha, with real outputs.

Sukanya Saha, Technology Consultant

11 min read

Beginner friendly

Why PySpark?

ShopKart's order files are small today. But a shop with millions of customers creates gigabytes a day, and pandas on one laptop runs out of memory. Spark solves this by splitting data into partitions and processing them in parallel.

📊 How Spark runs your code

Your PySpark code

DataFrame operations in Python

Driver

Builds and optimizes a plan (Catalyst)

Executors

Run tasks, one per partition, in parallel

Result

Shown, collected, or written to files

Every example in this course ran on PySpark 4.0.1 on a laptop, with ShopKart's real order files. The outputs are exactly what we got.

Install and start Spark

Terminal
$java -version # Spark needs Java 17 or 21
$python3.11 -m venv venv && source venv/bin/activate
$pip install pyspark==4.0.1 pandas pyarrow
$export PYSPARK_PYTHON=$(which python) # workers must use the same Python
PySpark · Python
from pyspark.sql import SparkSession

spark = (SparkSession.builder
         .appName("shopkart")
         .master("local[*]")                           # use every CPU core of this laptop
         .config("spark.ui.showConsoleProgress", "false")   # no progress bars in the output
         .getOrCreate())
spark.sparkContext.setLogLevel("ERROR")
print("Spark", spark.version)
Output
Spark 4.0.1

SparkSession is your entry point: every DataFrame comes from it. On Databricks it already exists as spark.

Your first DataFrame

Two months of ShopKart order files (one CSV per day) sit in data/orders/. Spark reads the whole folder at once:

PySpark · Python
orders = spark.read.csv("data/orders/", header=True, inferSchema=True)
print(orders.count(), "orders in", orders.rdd.getNumPartitions(), "partitions")
orders.show(3)
Output
5316 orders in 8 partitions
+--------+-----------+----------+--------+----------+---------+-------------------+
|order_id|customer_id|product_id|quantity|unit_price|   status|           order_ts|
+--------+-----------+----------+--------+----------+---------+-------------------+
|  101734|        166|        11|       1|      1899|DELIVERED|2026-10-21 19:04:58|
|  101735|        130|         8|       1|      3499|DELIVERED|2026-10-21 12:36:45|
|  101736|         90|         9|       1|       799|DELIVERED|2026-10-21 17:37:37|
+--------+-----------+----------+--------+----------+---------+-------------------+
only showing top 3 rows

5,316 rows, split into 8 partitions (pieces Spark processes in parallel, one per core here). A DataFrame is a table with named, typed columns, spread across those partitions.

Lazy evaluation: transformations vs actions

PySpark · Python
from pyspark.sql import functions as F

delivered = orders.filter(F.col("status") == "DELIVERED")   # transformation: nothing runs yet
print(type(delivered).__name__)
print(delivered.count())                                     # action: now Spark runs a job
Output
DataFrame
4146
Transformations (lazy: build the plan)Actions (run the plan)
select, filter/where, withColumn, groupBy, join, orderBy, distinctshow, count, collect, take, first, toPandas
Return a new DataFrame instantlywrite.parquet / csv / saveAsTable

filter returned a DataFrame immediately without reading anything. Only count() made Spark read the files. Waiting lets Spark optimize the whole chain at once, for example reading only the columns you use.

PySpark · Python
delivered.select("order_id", "status").explain()
Output
== Physical Plan ==
*(1) Filter (isnotnull(status#22) AND (status#22 = DELIVERED))
+- FileScan csv [order_id#17,status#22] Batched: false, DataFilters: [isnotnull(status#22), (status#22 = DELIVERED)], Format: CSV, Location: InMemoryFileIndex(1 paths)[file:/private/tmp/claude-501/-Users-sudiptabiswas-claude/f6c71fe0-f8b1..., PartitionFilters: [], PushedFilters: [IsNotNull(status), EqualTo(status,DELIVERED)], ReadSchema: struct<order_id:string,status:string>

explain() shows the physical plan: the filter is pushed into the file scan (DataFilters) and only two columns are read. You'll use this to debug slow jobs.

A real Spark 4 gotcha: inferSchema

Let's find orders with 2 or more items:

PySpark · Python
try:
    orders.filter(F.col("quantity") >= 2).count()
except Exception as e:
    print(type(e).__name__, "->", str(e).splitlines()[0][:150])

print(dict(orders.dtypes)["quantity"])     # inferSchema guessed: string!
Output
NumberFormatException -> [CAST_INVALID_INPUT] The value 'two' of the type "STRING" cannot be cast to "BIGINT" because it is malformed. Correct the value as per the syntax, or 
string

One file has a broken row where the supplier wrote two instead of 2. inferSchema saw it and decided the whole quantity column is text. Spark 4 turns on ANSI mode by default, so instead of silently returning wrong results it refuses to compare 'two' with a number. Lesson 2 fixes this properly with an explicit schema.

Spark and pandas

PySpark · Python
import pandas as pd

small = orders.limit(5).toPandas()      # Spark -> pandas (only for small results!)
print(type(small).__name__, small.shape)
Output
DataFrame (5, 7)

toPandas() pulls data to the driver as a pandas DataFrame: perfect for a small result to plot, dangerous on big data (it all has to fit in one machine's memory).

🎯 Interview questions on this topic

Try to answer out loud first, then tap to check.

Q1What is PySpark?Fresher
The Python API for Apache Spark, a distributed processing engine. You write DataFrame or SQL code in Python; Spark's driver builds an optimized plan and executors run tasks in parallel across partitions on one machine or a cluster.
Q2Transformations vs actions?Fresher
Transformations (select, filter, join, groupBy) define a new DataFrame lazily. Actions (count, show, collect, write) trigger execution of the whole plan. Laziness lets Spark optimize the full chain.
Q3Why avoid inferSchema in production?1–3 yrs
It needs an extra pass over the data, and types depend on whatever data arrives: a single bad value can turn a numeric column into a string and break or silently change downstream logic. Define an explicit schema (StructType) instead.
Q4What is a partition?1–3 yrs
A chunk of a DataFrame's rows processed by one task. Parallelism equals the number of partitions (limited by cores). Too few partitions underuse the cluster; too many tiny ones add overhead.
Q5What changed with ANSI mode in Spark 4?3+ yrs
spark.sql.ansi.enabled is true by default: invalid casts, overflow and divide-by-zero raise errors instead of returning NULL or wrong values. Safer data, but pipelines relying on silent NULLs need try_cast / try_ functions or explicit cleaning.

Key takeaways

  • PySpark lets the same Python code scale from a laptop to a cluster.
  • Lazy plans plus explain() are how you understand what Spark does.
  • Explicit schemas beat inferSchema: we saw why.
  • Keep toPandas() for small results.

Frequently asked questions

What is PySpark?

PySpark is the Python API for Apache Spark, an engine that processes big data by splitting it across many CPU cores or machines. You write Python; Spark plans the work and runs it in parallel.

Do I need a cluster to learn PySpark?

No. pip install pyspark and run it in local mode on your laptop, as this course does. The same code runs unchanged on Databricks, AWS EMR, Azure Synapse or Fabric, just with more machines.

PySpark or pandas?

pandas runs on one machine and must fit the data in memory: great up to a few GB. PySpark spreads work across cores and machines and handles terabytes. Many pipelines use PySpark for the heavy lifting and pandas for small final results.

What do I need installed?

Python (3.10–3.12 is safest) and Java 17 or 21 (Spark runs on the JVM). Then pip install pyspark. Make sure workers use the same Python as your script by setting PYSPARK_PYTHON.

Is this the same as the PySpark in your Databricks course?

Same library, deeper. The Databricks course shows PySpark inside Databricks; this course teaches PySpark on its own, from installing it to window functions and UDFs, so it works anywhere.

🧠 Quick check: PySpark basics

  1. 1. What does spark.read.csv(...).filter(...) do before you call an action?

  2. 2. Which is an action?

  3. 3. Why did quantity >= 2 fail in our run?

  4. 4. What does local[*] mean?

PySpark for Beginners

Part 1 of 5: PySpark Tutorial for Beginners