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.

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

spark = SparkSession.builder.appName("DataFrameCreationDemo").getOrCreate()

# Method 1: From List of Tuples + Column Names
sales_data = [
("CUST01", "Female", 34, "Beauty", 1500.0),
("CUST02", "Male", 26, "Clothing", 850.0),
("CUST03", "Female", 42, "Electronics", 3200.0)
]
df_tuples = spark.createDataFrame(
sales_data,
schema=["customer_id", "gender", "age", "category", "amount"]
)
print("1. DataFrame from Tuples:")
df_tuples.show()

# Method 2: From List of Dictionaries (keys automatically become column names)
dict_data = [
{"store_id": 101, "city": "Mumbai", "active": True},
{"store_id": 102, "city": "Delhi", "active": False}
]
df_dict = spark.createDataFrame(dict_data)
print("2. DataFrame from Dictionaries:")
df_dict.show()

# Method 3: Distributed Synthetic Data via spark.range()
df_range = spark.range(1, 6).toDF("order_id")
print("3. DataFrame from spark.range():")
df_range.show()

```

EXPECTED OUTPUT:

```

hide

1. DataFrame from Tuples:
+-----------+------+---+-----------+------+
|customer_id|gender|age| category|amount|
+-----------+------+---+-----------+------+
| CUST01|Female| 34| Beauty|1500.0|
| CUST02| Male| 26| Clothing| 850.0|
| CUST03|Female| 42|Electronics|3200.0|
+-----------+------+---+-----------+------+

2. DataFrame from Dictionaries:
+------+------+--------+
|active| city|store_id|
+------+------+--------+
| true|Mumbai| 101|
| false| Delhi| 102|
+------+------+--------+

3. DataFrame from spark.range():
+--------+
|order_id|
+--------+
| 1|
| 2|
| 3|
| 4|
| 5|
+--------+

```

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()

# Method 4A: Standardized Read API (Preferred in Production)
df_csv = (
spark.read
.format("csv")
.option("header", True) # Treats 1st row as column names (else _c0, _c1...)
.option("inferSchema", True) # Scans file to detect int/double instead of string
.load("s3a://pyspark420/datasets/public/retail_sales_dataset.csv")
)
print("4A. DataFrame from a CSV file in S3:")
df_csv.printSchema()
df_csv.show(5)

# Method 4B: Reading Parquet (Schema & Types are Embedded — No header/inferSchema needed!)
df_parquet = spark.read.parquet("s3a://pyspark420/datasets/public/retail_sales.parquet")
print("4B. DataFrame from a Parquet file in S3:", df_parquet.count(), "rows,", len(df_parquet.columns), "columns")

# Method 5: Converting a Small Pandas DataFrame -> PySpark DataFrame
import pandas as pd
pdf = pd.DataFrame({"dept": ["IT", "HR"], "headcount": [120, 35]})
df_from_pandas = spark.createDataFrame(pdf)
print("5. DataFrame from Pandas:")
df_from_pandas.show()

```

EXPECTED OUTPUT:

```

hide

4A. DataFrame from a CSV file in S3:
root
|-- transaction_id: integer (nullable = true)
|-- date: date (nullable = true)
|-- customer_id: string (nullable = true)
|-- gender: string (nullable = true)
|-- age: integer (nullable = true)
|-- category: string (nullable = true)
|-- quantity: integer (nullable = true)
|-- price_per_unit: double (nullable = true)
|-- total_amount: double (nullable = true)

+--------------+----------+-----------+------+---+-----------+--------+--------------+------------+
|transaction_id| date|customer_id|gender|age| category|quantity|price_per_unit|total_amount|
+--------------+----------+-----------+------+---+-----------+--------+--------------+------------+
| 1|2026-01-23| CUST01|Female| 53|Electronics| 4| 1800.0| 7200.0|
| 2|2026-01-24| CUST02|Female| 60| Clothing| 4| 1200.0| 4800.0|
| 3|2026-03-25| CUST03| Male| 26| Beauty| 1| 500.0| 500.0|
| 4|2026-02-13| CUST04| Male| 61|Electronics| 1| 3200.0| 3200.0|
| 5|2026-02-04| CUST05|Female| 49| Clothing| 1| 250.0| 250.0|
+--------------+----------+-----------+------+---+-----------+--------+--------------+------------+
only showing top 5 rows

4B. DataFrame from a Parquet file in S3: 20 rows, 9 columns
5. DataFrame from Pandas:
+----+---------+
|dept|headcount|
+----+---------+
| IT| 120|
| HR| 35|
+----+---------+

```

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'!).
2. Cost of inferSchema=True:
Setting inferSchema=True forces Spark to run an extra full-file scan job immediately to guess data types. On 500 GB CSVs, always pass an explicit StructType schema instead.
3. Immutability Trap: Writing df.filter(df['age'] > 30) without assigning it to a variable (filtered_df = ...) throws away the result because df itself never changes!

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

PySpark tutorial: all lessons · All tutorials · Try the free PySpark compiler · Practice challenges · Beginner tutorial: learn PySpark step by step