Sub topic 4
Looking at your data
This chapter covers the ways to inspect a DataFrame in a Databricks notebook: display, show, printSchema, and a few related calls. It assumes you can attach a notebook to compute, know basic Python or SQL, and understand rows, columns, and types. Lazy evaluation gets its own chapter. Here you only need to know that inspecting data often triggers real work.
Why inspection matters
A DataFrame is a description of data, not a block of data in memory. Before you transform it, you need to check three things: the column names and types, a sample of the values, and the size of the data. Each inspection call answers one of these questions at a different cost.
Start with a small DataFrame
The examples in this chapter use this DataFrame. It has a string date column that we convert to a real date, and one null amount.
from pyspark.sql import functions as F
orders = spark.createDataFrame(
[
(1, "alice", "2024-01-05", 120.0),
(2, "bob", "2024-01-06", 75.5),
(3, "alice", "2024-02-10", 30.0),
(4, "carol", "2024-02-11", None),
],
"order_id INT, customer STRING, order_date STRING, amount DOUBLE",
)
orders = orders.withColumn("order_date", F.to_date("order_date"))
orders.printSchema()
display(orders)spark is the session Databricks creates for you in every notebook. The third argument to createDataFrame is a DDL-style schema string. DDL means data definition language, the syntax SQL uses in CREATE TABLE.
printSchema: the cheapest check
printSchema() prints the column names, types, and nullability as a tree. It reads only metadata, so it is fast and starts no job over the data.
root
|-- order_id: integer (nullable = true)
|-- customer: string (nullable = true)
|-- order_date: date (nullable = true)
|-- amount: double (nullable = true)Run it after every read and after every step that changes types. If a column you expected to be a number shows as string, find out why before going further. A common cause is a CSV read without an explicit schema, or a column with a stray text value.
The schema attribute and the dtypes attribute give the same information as Python objects. They are useful when you need to branch on a type in code.
print(orders.dtypes)
print(orders.columns)display: the notebook-native view
display(df) is a Databricks function, not part of open-source PySpark. It renders the DataFrame as an interactive table. In that table you can sort, scroll, and switch to a chart with the plus button under the output. It also offers a data profile tab that shows summary statistics per column.
Keep these points in mind:
displaylimits how many rows it brings back to the notebook. Large results are cut off, so you see a sample, not everything.- Sorting in the table UI may re-run the query, depending on the result size.
displayexists only in Databricks notebooks. Code that must also run in plain PySpark scripts or tests should not depend on it.- It does not return a DataFrame. Use it as the last statement in a cell, not in the middle of a chain.
show: plain text output
show() is standard PySpark and prints a text table to the cell output. It works anywhere Spark runs.
orders.show()
orders.show(2)
orders.show(truncate=False)
orders.show(vertical=True)The arguments behave as follows:
| Call | Effect |
|---|---|
| `show()` | Prints the first 20 rows. Strings longer than 20 characters are cut off. |
| `show(n)` | Prints the first `n` rows. |
| `show(truncate=False)` | Prints full string values. Use it for long text or JSON columns. |
| `show(vertical=True)` | Prints one line per column value. Use it for wide tables. |
Nulls appear as null in both show and display. An empty string appears as blank. Telling them apart matters later, when you handle missing values.
Sampling rows without a full scan
Some calls bring rows back to the driver. The driver is the machine that runs your notebook code and coordinates the cluster.
first_rows = orders.limit(2)
display(first_rows)
as_list = orders.take(2)
print(as_list)
one = orders.first()
print(one["customer"])limit(n)is a transformation. It returns a new DataFrame with at mostnrows.take(n)andhead(n)are actions. They return a Python list ofRowobjects.first()returns a singleRow.collect()returns every row to the driver. Avoid it on large data, because it can exhaust driver memory.
The rows limit returns are not guaranteed to be the first rows in any meaningful order. Spark does not promise a row order unless you sort. If you need the top rows by some value, call orderBy first.
Counting and describing
print(orders.count())
orders.describe("amount").show()
orders.select("amount").summary().show()count() is an action that reads the data, so on a large table it can be slow. describe returns count, mean, standard deviation, minimum, and maximum. summary adds percentiles. Both skip nulls, so the count they report for amount is 3, not 4.
What triggers work
Different inspection calls cost different amounts. This diagram shows the split.
Each call in the lower group executes the whole chain of transformations behind the DataFrame, as far as needed to produce the result. If the DataFrame comes from an expensive join, every count() and show() pays for the join again unless you cache the result. Caching is covered in a later chapter.
Common errors
- Reading
show()output as the whole data. It shows 20 rows by default. A clean top 20 says nothing about the other millions. - Trusting inferred types. A column that looks numeric in
displaycan still be a string. CheckprintSchema(). - Confusing null with the text "null". A string column can hold the literal text
null, whichisNull()does not match. - Calling
displaymid-chain.display(df).filter(...)fails becausedisplayreturns nothing useful. Build the chain first, then display the result. - Using
collect()to look at data. It moves every row to the driver. Uselimitortakeinstead.
Putting it together
A good inspection routine for a new DataFrame takes four steps:
- Run
printSchema()to check names and types. - Run
display(df.limit(100))to look at real values. - Run
describeon the key numeric columns to spot odd ranges. - Run
count()once you know the cost is acceptable.
Exercise
You run orders.show() on a table with 50 million rows, and the output looks fine. A teammate says the data is verified. What is wrong with that conclusion, and which cheaper first check should you have done before looking at rows?
Show answer
show() prints only the first 20 rows, and Spark does not guarantee which rows those are, so it says almost nothing about the other 50 million. The cheaper first check is printSchema(), which reads only metadata and confirms names and types. After that, use display(df.limit(100)) and describe on numeric columns, and run count() only if you need the exact number.
Exercise
Why does orders.describe("amount") report a count of 3 for the example DataFrame, even though it has 4 rows?
Show answer
One row has a null amount, and describe skips nulls when it computes statistics, so only 3 values are counted.