Displaying & Exploring DataFrames

Spark tutorial · PySpark.in

DATAFRAME BASICS • CHAPTER 2 | PYSPARK.IN CURRICULUM

Displaying & Exploring DataFrames in PySpark

show(), display(), head(), take(), printSchema(), describe() vs. summary() & Preventing collect() Driver OOM

1. Viewing Rows Safely: show(), display(), head() & take()

Because a PySpark DataFrame can contain billions of rows across a cluster, you should never print the entire DataFrame. Instead, PySpark provides lightweight preview actions that fetch only a small sample back to the Driver:

Method / Property

Type

What It Returns & Default Behavior

df.show(n=20, truncate=True, vertical=False)

Action

Prints top n rows (default 20) as an ASCII table. Long strings (>20 chars) are cut off unless truncate=False. Returns None!

df.display() / display(df)

Databricks Action

Databricks-only interactive HTML table with built-in sorting, filtering, charting, and CSV download (not in open-source Spark).

df.head(n) / df.take(n)

Action

Returns the first n records as a Python List of Row objects (safe for grabbing 1–10 values into Python variables).

df.first()

Action

Shortcut for df.head(1)[0] — returns the very first Row object.

df.columns / df.dtypes

Metadata Property

Instant metadata lookup (Zero Spark Job!). Returns list of column names or (col_name, data_type) tuples.

df.printSchema()

Metadata Method

Prints a tree view of column names, data types, and nullable flags. Does NOT show row counts (unlike Pandas df.info()).

df.count()

Action

Triggers a distributed Spark job to return the exact total number of rows across all partitions.

2. Production Danger: Why collect() Crashes Your Driver Node

One of the most expensive mistakes beginners make when transitioning from Pandas is calling df.collect() on large tables. While show(20) and take(5) read only the first partition until they have enough rows, collect() forces every Executor to serialize and transfer 100% of the dataset into the single Driver node's RAM.

Figure 1: Why show()/take() stay fast and safe while collect() triggers Driver OutOfMemory (OOM) crashes (High-Res Zoomable PNG).

3. Statistical Profiling: describe() vs. summary()

Both df.describe() and df.summary() compute summary statistics across numeric and string columns, returning a new DataFrame:

4. Runnable PySpark Code: Full DataFrame Exploration Toolkit

Snippet 1: Exploring Structure, Custom show() Formatting, describe() vs. summary()

```

from pyspark.sql import SparkSession

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

data = [
("TXN001", "Female", 34, "Beauty & Wellness Products", 1500.0),
("TXN002", "Male", 24, "Clothing & Apparel", 800.0),
("TXN003", "Female", 41, "Consumer Electronics", 3200.0),
("TXN004", "Male", 38, "Beauty & Wellness Products", 2100.0),
("TXN005", "Female", 29, "Consumer Electronics", 1900.0)
]
df = spark.createDataFrame(data, ["txn_id", "gender", "age", "category", "amount"])

# 1. Instant Metadata Inspection (No Spark Job Triggered)
print("Columns :", df.columns)
print("Dtypes :", df.dtypes)
df.printSchema()

# 2. Clean Table Display (truncate=False prevents cutting off long category names)
df.show(3, truncate=False)

# 3. Vertical Display (Awesome for wide tables with 50+ columns!)
df.show(1, truncate=False, vertical=True)

# 4. Statistical Summary: describe() vs summary()
print("=== describe() (Fast Basic Stats) ===")
df.select("age", "amount").describe().show()

print("=== summary() (Includes 25%, 50%, 75% Percentiles) ===")
df.select("age", "amount").summary("count", "mean", "50%", "max").show()

# 5. Safe Extraction of First Row into Python
first_row = df.first()
print("First Transaction ID:", first_row["txn_id"], "| Amount:", first_row["amount"])

```

EXPECTED OUTPUT:

```

hide

Columns : ['txn_id', 'gender', 'age', 'category', 'amount']
Dtypes : [('txn_id', 'string'), ('gender', 'string'), ('age', 'bigint'), ('category', 'string'), ('amount', 'double')]
root
|-- txn_id: string (nullable = true)
|-- gender: string (nullable = true)
|-- age: long (nullable = true)
|-- category: string (nullable = true)
|-- amount: double (nullable = true)

+------+------+---+--------------------------+------+
|txn_id|gender|age|category |amount|
+------+------+---+--------------------------+------+
|TXN001|Female|34 |Beauty & Wellness Products|1500.0|
|TXN002|Male |24 |Clothing & Apparel |800.0 |
|TXN003|Female|41 |Consumer Electronics |3200.0|
+------+------+---+--------------------------+------+
only showing top 3 rows

-RECORD 0------------------------------
txn_id | TXN001
gender | Female
age | 34
category | Beauty & Wellness Products
amount | 1500.0
only showing top 1 row

=== describe() (Fast Basic Stats) ===
+-------+-----------------+------------------+
|summary| age| amount|
+-------+-----------------+------------------+
| count| 5| 5|
| mean| 33.2| 1900.0|
| stddev|6.833739825307955| 880.3408430829505|
| min| 24| 800.0|
| max| 41| 3200.0|
+-------+-----------------+------------------+

=== summary() (Includes 25%, 50%, 75% Percentiles) ===
+-------+----+------+
|summary| age|amount|
+-------+----+------+
| count| 5| 5|
| mean|33.2|1900.0|
| 50%| 34|1900.0|
| max| 41|3200.0|
+-------+----+------+

First Transaction ID: TXN001 | Amount: 1500.0

```

Common Beginner Anti-Pattern: Never Assign .show() to a Variable!

WRONG: rdf = df.select(['txn_id', 'amount']).show()
Why it breaks: .show() prints to console and returns None. Now rdf is NoneType, so any next line like rdf.count() will fail with AttributeError: 'NoneType' object has no attribute 'count'.
CORRECT: rdf = df.select(['txn_id', 'amount']) and then call rdf.show() on the next line.

5. MNC Interview Questions (Chapter 2)

Q1. What is the difference between df.show(), df.take(n), and df.collect()?

Answer: df.show() formats and prints the top 20 rows to stdout and returns None. df.take(n) safely brings only the first n rows back to the Driver as a Python list of Row objects. df.collect() brings ALL rows from the entire cluster into Driver RAM—causing OutOfMemory crashes on big datasets.

Q2. Why does df.describe() not include 25%, 50%, and 75% percentiles like Pandas does?

Answer: Computing basic stats (count, mean, min, max) is cheap and easily parallelizable across partitions. Calculating percentiles requires extra memory/quantile estimation across distributed nodes. Spark keeps describe() lightweight and provides summary() when approximate quantiles are explicitly needed.

Q3. Does df.printSchema() or df.columns trigger a Spark Job?

Answer: No. Both read structural metadata directly from the Driver's Catalyst Logical Plan without scanning a single row of data on Executors.

More Spark tutorials

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