Sub topic 12
Moving data between pandas, Polars, DuckDB, and Spark
This chapter assumes you have read the earlier chapters on the four tools and on Parquet and Arrow. It also assumes you can write basic pandas and SQL. Mixing tools in one pipeline works well when you know where data is copied and where it is shared.
Why conversion is usually cheap
Polars, DuckDB, and modern pandas can all read and write Apache Arrow, a standard in-memory columnar layout. When two tools agree on that layout, a conversion can often reuse buffers instead of rebuilding every value. Conversions that go through Python objects or row-by-row formats are much slower.
pandas, Polars, and DuckDB
DuckDB can query a pandas or Polars DataFrame by its Python variable name. It returns results with .df() (pandas), .pl() (Polars), or .arrow() (Arrow table).
import duckdb
import pandas as pd
import polars as pl
pdf = pd.DataFrame({"region": ["eu", "us", "eu"], "revenue": [10, 20, 5]})
# pandas -> DuckDB -> Polars
plf = duckdb.sql(
"SELECT region, sum(revenue) AS revenue FROM pdf GROUP BY region"
).pl()
# Polars -> pandas
back_to_pandas = plf.to_pandas()
# pandas -> Polars directly
plf2 = pl.from_pandas(pdf)
print(back_to_pandas)
print(plf2.shape)The .pl() and .to_pandas() calls need pyarrow installed.
Spark
Spark runs in separate JVM processes, so data must cross a process boundary. Enabling Arrow makes that crossing much faster.
import pandas as pd
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("interop").getOrCreate()
spark.conf.set("spark.sql.execution.arrow.pyspark.enabled", "true")
pdf = pd.DataFrame({"region": ["eu", "us", "eu"], "revenue": [10, 20, 5]})
sdf = spark.createDataFrame(pdf) # pandas -> Spark
summary = sdf.groupBy("region").sum("revenue")
local = summary.toPandas() # Spark -> pandas
print(local)Polars has no direct Spark bridge. Go through pandas (plf.to_pandas()), or write Parquet and read it back.
Choosing a handoff method
| Handoff | Typical method | Cost |
|---|---|---|
| pandas and Polars | `pl.from_pandas`, `.to_pandas()` | Low to moderate. May copy data, depending on dtypes. |
| DuckDB and pandas or Polars | Variable name in SQL, `.df()`, `.pl()` | Low. Arrow-based. |
| Any tool and Spark, same machine | Parquet file | Disk I/O, but robust. |
| Spark to the driver | `toPandas()` | Collects the whole result into one process. |
Common errors
- Collecting too much.
toPandas()pulls every row to the driver. Aggregate or filter in Spark first, or you will run out of memory. - Converting lazy to eager too early. Calling
.collect()or.df()in the middle of a pipeline throws away the optimizer's chance to skip columns and rows. Convert at the end of a stage. - Assuming zero copy. Nullable integers, strings, and object columns in pandas often need copying or type changes. Check dtypes after a round trip.
- Missing
pyarrow. Many conversion methods raise an import error without it. - Going through pandas out of habit. When the target is DuckDB or Polars, hand over Arrow or Parquet instead. The pandas step adds a copy and may change dtypes.
Exercise
A pipeline aggregates 2 billion rows in Spark, then calls toPandas() on the full unaggregated result to plot it. It fails with an out-of-memory error. What should you change?
Show answer
Do the aggregation in Spark and call toPandas() only on the small summarized result, because toPandas() collects every row into the single driver process. If the plot needs more rows, filter or sample in Spark first.