Sub topic 19
Moving data to pandas safely
This chapter covers how to convert a Spark DataFrame to pandas without crashing the driver, and how to avoid converting at all when you can. It assumes you can read and transform Spark DataFrames, and that you know the difference between transformations and actions from earlier chapters. Basic pandas knowledge helps.
Why conversion is risky
A Spark DataFrame is split into partitions that live on worker nodes. A pandas DataFrame is a single Python object held in the memory of one machine. Calling toPandas() is therefore an action that collects every row to the driver and builds one in-memory table.
Three things can go wrong:
- Out-of-memory errors. The driver may have far less memory than the cluster as a whole. A 50 GB result will not fit on a driver with 16 GB.
- Slow cells. All the data crosses the network to one node, and one process builds the pandas object. This work is not parallel.
- Silent loss of scale. Code that works on a sample can fail on the full table. Pandas operations then run on one core, even though the cluster is large.
The usual rule is to reduce the data in Spark first, then convert the small result.
The basic conversion
The example below uses the orders DataFrame from earlier chapters. It aggregates in Spark and converts only the summary.
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",
).withColumn("order_date", F.to_date("order_date"))
summary = (
orders
.groupBy("customer")
.agg(F.sum("amount").alias("total_amount"))
)
pdf = summary.toPandas()
print(pdf.dtypes)
print(pdf)The Spark work (the shuffle for groupBy) runs on the cluster. Only three rows reach the driver.
Strategies for keeping the result small
Apply these before you call toPandas().
- Filter early. Keep only the rows you need.
- Select only needed columns. Wide tables cost memory for every column.
- Aggregate. Plots and reports rarely need row-level data.
- Limit. Use
limit(n)to cap the row count. - Sample. Use
samplefor exploratory work.
sample_pdf = (
orders
.select("customer", "amount")
.filter(F.col("amount").isNotNull())
.sample(fraction=0.5, seed=42)
.limit(1000)
.toPandas()
)
print(len(sample_pdf))sample is approximate. The fraction is the probability that each row is kept, so the returned row count varies. Set seed to make the sample repeatable on the same data. limit after sample guarantees an upper bound.
limit versus sample
| Method | Rows returned | Representative? | Typical use |
|---|---|---|---|
| `limit(n)` | At most `n` | No. Often the first rows Spark finds | Quick look at the structure |
| `sample(fraction, seed)` | About `fraction` of the rows | Yes, for random sampling | Exploration and plotting |
| `filter` plus aggregate | Depends on the grouping | Exact for the question you ask | Reports and features |
A limit without an orderBy gives no guarantee about which rows you get. Do not draw statistical conclusions from it.
Data type behavior
Spark and pandas types do not match one to one. Check pdf.dtypes after converting.
| Spark type | Typical pandas result | Gotcha |
|---|---|---|
| `INT`, `BIGINT` | `int32` or `int64` | Becomes `float64` if the column contains nulls |
| `DOUBLE` | `float64` | Null becomes `NaN` |
| `STRING` | `object` | Null becomes `None` |
| `DATE` | `object` (Python `date`) | Not `datetime64` unless you convert it |
| `TIMESTAMP` | `datetime64[ns]` | Time zone handling depends on the session time zone |
| `DECIMAL` | `object` (Python `Decimal`) | Arithmetic and plotting can be awkward |
The null handling matters. An integer column with a single null becomes a float column in pandas. If you need integer semantics, cast in Spark and fill or drop nulls first, or convert to pandas's nullable integer type afterwards.
pdf = orders.toPandas()
pdf["order_date"] = pdf["order_date"].astype("datetime64[ns]")
pdf["amount"] = pdf["amount"].fillna(0.0)
print(pdf.dtypes)Apache Arrow
Spark can transfer data to pandas using Apache Arrow, a columnar in-memory format. This is much faster than the row-by-row path. In recent Databricks Runtime versions Arrow-based transfer is typically on by default, but you can check and set it explicitly.
print(spark.conf.get("spark.sql.execution.arrow.pyspark.enabled"))
spark.conf.set("spark.sql.execution.arrow.pyspark.enabled", "true")If a column type is not supported by Arrow, Spark can fall back to the slower path. The fallback setting is spark.sql.execution.arrow.pyspark.fallback.enabled. Arrow speeds up the transfer but does not reduce the memory needed on the driver.
Checking the size before you convert
Do not guess. Count rows and estimate the footprint first. The count() is itself an action, so do it on the already-reduced DataFrame.
candidate = orders.select("customer", "amount")
row_count = candidate.count()
print("rows:", row_count)
if row_count > 1_000_000:
raise ValueError("Too many rows for toPandas(). Aggregate or sample first.")
pdf = candidate.toPandas()
print(pdf.memory_usage(deep=True).sum(), "bytes")Pandas often uses several times the memory of the raw data, especially for string columns stored as Python objects. A rough working budget is to keep the converted result well under a quarter of the driver memory.
The driver result size limit
Spark also limits the total size of results collected to the driver, set by spark.driver.maxResultSize. If a conversion exceeds it, the job fails with an error saying the total size of serialized results is larger than that limit. Raising it moves the problem to driver memory. Reducing the data is the better fix.
Alternatives to toPandas
If the data is too large for one machine, keep it distributed.
- pandas API on Spark.
pyspark.pandasoffers a pandas-like interface that runs on Spark. Useorders.pandas_api()to convert a DataFrame. Operations run across the cluster, but ordering and some pandas behaviors differ. mapInPandasandapplyInPandas. These apply a pandas function to batches or to each group. The function runs on the workers, so the full data is never collected on the driver.- Spark built-ins. Most analysis can be done with functions from
pyspark.sql.functions, which is the cheapest option.
import pandas as pd
def add_flag(batches):
for batch in batches:
batch["is_large"] = batch["amount"] > 50
yield batch
flagged = orders.select("order_id", "amount").mapInPandas(
add_flag,
schema="order_id INT, amount DOUBLE, is_large BOOLEAN",
)
flagged.show()This function runs on each batch of rows in parallel. The pandas code sees only a slice of the data at a time.
Going the other direction
Use spark.createDataFrame(pdf) to turn a pandas DataFrame back into a Spark DataFrame. The pandas data starts on the driver, so this does not scale beyond driver memory either. Pass an explicit schema if types are ambiguous, particularly for columns that are all null or contain mixed types.
import pandas as pd
local = pd.DataFrame({"customer": ["alice", "bob"], "country": ["US", "DE"]})
customers = spark.createDataFrame(local, "customer STRING, country STRING")
customers.show()Common errors
- Out-of-memory or the driver restarting. The result was too large. Aggregate or sample before converting.
maxResultSizeerror. Same cause. Reduce the data.- Unexpected float columns. Nulls in integer columns. Handle nulls first.
- Slow
toPandas()on a small result. The cost may be in the upstream plan (a large join or shuffle), which runs when the action triggers. Useexplain()to inspect it. - Repeated conversions. Each call to
toPandas()reruns the full plan unless you cache the DataFrame. Convert once and reuse the pandas object.
Exercises
Exercise
You have a 200-million-row events DataFrame and want a bar chart of event counts per day with matplotlib. Describe how you would get the data into pandas.
Show answer
Group by the event date in Spark and count, which yields one row per day. Call toPandas() on that small result and pass it to matplotlib. Converting the raw 200 million rows is unnecessary and risks an out-of-memory error on the driver.
Exercise
After toPandas(), an INT column called quantity has dtype float64. What is the likely cause, and name two ways to fix it?
Show answer
The column contains at least one null, and pandas' default integer dtype cannot hold missing values, so it uses float64 with NaN. Fix it by filling or dropping nulls in Spark before converting (for example with fillna or dropna), or by converting in pandas with the nullable type, such as pdf["quantity"].astype("Int64").
Exercise
Why does df.limit(100).toPandas() not give you a random sample of 100 rows, and what would you use instead?
Show answer
limit returns whichever 100 rows Spark finds first, which depends on partition order and is not random. Use sample(fraction, seed) for a random sample, and add limit afterwards if you need a hard cap on the row count.