Introduction to PySpark DataFrames & Creation
Spark tutorial · PySpark.in
DATAFRAME BASICS • CHAPTER 1 | PYSPARK.IN CURRICULUM Introduction to PySpark DataFrames & DataFrame Creation Distributed Tabular Abstraction, Immutability, Pandas vs. PySpark & All 5 Production Creation Methods |
1. What Is a PySpark DataFrame?
A PySpark DataFrame is a distributed, immutable collection of data organized into named columns—conceptually identical to a relational database table or a Pandas DataFrame, except its rows are partitioned across multiple worker nodes in a cluster.
- Schema-Backed: Every column has a strict name and data type (StringType, IntegerType, DoubleType, DateType), allowing Spark's Catalyst Optimizer to optimize queries automatically.
- Immutable by Design: You can never modify a PySpark DataFrame in place (unlike Pandas inplace=True). Every transformation returns a brand-new DataFrame reference, preserving lineage for fault tolerance.
- Lazy Evaluation: Creating or transforming a DataFrame builds a logical execution plan; actual computation runs only when an Action (show(), count(), write()) is triggered.
2. Pandas DataFrame vs. PySpark DataFrame
Feature | Pandas DataFrame | PySpark DataFrame |
Execution Model | Single-machine (runs in local RAM on 1 CPU core by default). | Distributed across cluster Worker Nodes (multi-core, multi-machine). |
Mutability | Mutable (supports in-place edits like df['col'] = ...). | Strictly Immutable (every transformation creates a new DataFrame). |
Evaluation Style | Eager (executes immediately line by line). | Lazy (optimizes full query plan via Catalyst before execution). |
Default String Type | Stored as 'object' or StringDtype in Python. | Stored as 'string' (UTF-8 binary inside Tungsten UnsafeRow). |
Row Indexing | Has an explicit row index (0, 1, 2... or custom labels). | No built-in row index (order is not guaranteed without orderBy()). |
Ideal Data Volume | MBs to a few GBs (fits comfortably in single-machine RAM). | GBs to Petabytes (production Data Lakes & Lakehouses). |
3. How PySpark Creates Distributed DataFrames

Figure 1: PySpark DataFrame creation pipeline from in-memory collections and cloud storage into cluster partitions (High-Res Zoomable PNG).
4. Five Ways to Create a DataFrame in PySpark
Method 1 — From a Python List of Tuples (spark.createDataFrame()): Most common for unit tests, small lookup tables, and browser tutorials.
Method 2 — From a List of Dictionaries or Row Objects: Useful when working with nested JSON-like Python payloads.
Method 3 — Using spark.range(): Generates millions of synthetic rows directly on Worker Nodes without loading anything into Driver RAM—perfect for benchmarking.
Snippet 1: Creating DataFrames from Lists, Dictionaries & spark.range() (Runnable) ``` from pyspark.sql import SparkSession ``` |
EXPECTED OUTPUT: ``` hide 1. DataFrame from Tuples: ``` |
Method 4 — From External Files (CSV, JSON, Parquet, Delta): In real data engineering pipelines, 99% of DataFrames are loaded from cloud storage (AWS S3, Azure ADLS Gen2, Databricks Volumes, or HDFS). PySpark supports both shorthand (spark.read.csv()) and the standardized spark.read.format().option().load() API.
Snippet 2: Loading CSV & Parquet Files from S3 + Converting from Pandas (Runnable) ``` from pyspark.sql import SparkSession spark = SparkSession.builder.appName("DataFrameCreationDemo").getOrCreate() ``` |
EXPECTED OUTPUT: ``` hide 4A. DataFrame from a CSV file in S3: ``` |
Try it: both sample files sit in a public, read-only S3 folder on PySpark.in, so the Run button reads them for real. In your own project, replace the path with your bucket (for example s3a://your-company-bucket/raw/sales/2026-01.csv); on EMR, Glue or Databricks the cluster's IAM role or instance profile grants the read access.
3 Critical Production Gotchas When Creating DataFrames 1. Without header=True & inferSchema=True: Spark names columns _c0, _c1, _c2 and assigns every column the string data type (NOT Pandas 'object'!). |
5. MNC Interview Questions (Chapter 1)
Q1. Why are PySpark DataFrames immutable, and how does this help in distributed computing?
Answer: Immutability guarantees thread-safety across hundreds of parallel tasks and makes fault-tolerant Lineage recovery possible. Because parent DataFrames never mutate, Spark can deterministically recompute any lost partition from its parent transformation.
Q2. Why should you avoid inferSchema=True on massive production CSV files?
Answer: inferSchema=True triggers an immediate extra Spark job that scans the file to infer column types (doubling I/O time). Worse, a single corrupt string value (e.g., 'N/A') in an integer column silently forces the entire column to StringType. Explicit schemas are faster and safer.
Q3. What is the risk of creating a huge PySpark DataFrame via spark.createDataFrame(python_list)?
Answer: The Python list or Pandas DataFrame lives entirely inside the Driver node's RAM before being serialized and shipped to Executors. Creating DataFrames from large in-memory Python objects can trigger a Driver OutOfMemory (OOM) crash.
More Spark tutorials
- Spark SQL Tutorial: Run SQL Queries in PySpark
- Spark SQL Queries in PySpark: spark.sql() Examples
- Registering UDFs in SQL
- PySpark Joins
- Broadcast Join and Skew Join in PySpark
- PySpark SQL Functions: col, lit, when (CASE WHEN)
PySpark tutorial: all lessons · All tutorials · Try the free PySpark compiler · Practice challenges · Beginner tutorial: learn PySpark step by step