Sub topic 12
Moving data between pandas, Polars, DuckDB, and Spark
This chapter assumes you can read basic pandas and SQL, and that you know what a DataFrame and a Parquet file are. The earlier chapters on columnar formats and the four tools are background.
Real pipelines rarely use one tool. You might read with DuckDB, reshape with Polars, hand the result to a pandas-only plotting library, and write Parquet for Spark. Each handoff has a cost, and some conversions can quietly change your data. This chapter covers the main paths, what each one costs, and where types go wrong.
Two ways to hand over data
There are two kinds of handoff:
- In-process conversion. The tools share a Python process and exchange memory, usually as Apache Arrow. This is fast, and often copies little or no data.
- Files. One tool writes Parquet and another reads it. This is slower, but it works across processes, machines, and languages, and it is the only practical route into a Spark cluster.
Arrow is a columnar in-memory format. Polars uses it as its native layout. DuckDB can read and produce Arrow tables, and pandas can use Arrow-backed columns and convert to and from Arrow tables. Because the layouts agree, a conversion can often reuse buffers instead of rewriting each value.
pandas, Polars, and DuckDB in one process
DuckDB can query a pandas DataFrame by its variable name. This is called a replacement scan: DuckDB looks up the name in your Python scope and reads the DataFrame in place, without loading it into a separate table first. DuckDB can return results as pandas (.df()), Polars (.pl()), or Arrow.
import duckdb
import pandas as pd
import polars as pl
import pyarrow as pa
pdf = pd.DataFrame({"region": ["eu", "us", "eu"], "revenue": [10, 20, 5]})
# pandas -> Polars
plf = pl.from_pandas(pdf)
# Polars -> Arrow -> pandas
table = plf.to_arrow()
back = table.to_pandas()
# DuckDB reads pandas, Polars, and Arrow objects by variable name
by_region = duckdb.sql(
"SELECT region, sum(revenue) AS revenue FROM plf GROUP BY region"
).pl()
# Arrow -> Polars
again = pl.from_arrow(pa.Table.from_pandas(pdf))
print(by_region.sort("region"))
print(back.dtypes)
print(again.schema)The functions to remember:
| From | To | Call |
|---|---|---|
| pandas | Polars | `pl.from_pandas(pdf)` |
| Polars | pandas | `plf.to_pandas()` |
| Polars | Arrow | `plf.to_arrow()` |
| Arrow | Polars | `pl.from_arrow(table)` |
| pandas | Arrow | `pa.Table.from_pandas(pdf)` |
| DuckDB result | pandas | `.df()` |
| DuckDB result | Polars | `.pl()` |
The pl.from_pandas, .to_pandas(), and .pl() conversions need pyarrow installed. If one fails with an import error, install pyarrow first.
What "zero-copy" really means
Zero-copy means the receiving tool uses the same memory buffers instead of duplicating them. It is possible only when both sides store a column the same way. In practice:
- Polars to Arrow is usually cheap, because Polars already stores Arrow-style columns.
- pandas columns stored as NumPy arrays generally need a copy to become Arrow, because the layouts differ. A numeric column without missing values is the most likely to be cheap.
- pandas columns of Python
objectstrings are the worst case. Each string is a separate Python object, so conversion visits every value. - DuckDB reading a pandas DataFrame avoids copying the whole frame into a DuckDB table, but it still converts columns as it scans them.
If memory is tight, do not assume a conversion is free. A conversion that copies a 6 GB frame needs room for both copies at once. To save memory, delete the source reference after converting, or convert only the columns you need.
Where the data changes
Conversions move values, but they can also change types. These are the usual problems:
- Integers with missing values. A NumPy-backed pandas integer column cannot hold nulls, so it becomes
float64withNaN. Going to Polars, thoseNaNvalues are treated as floating-point numbers, not nulls, unless you convert them. Use pandas nullable dtypes (Int64) or Arrow-backed dtypes to keep integer nulls intact. - The index. Polars and Arrow have no row index.
pl.from_pandasdrops the index by default, so reset it into a column first if it carries information. - Time zones and precision. Timestamps can differ in unit (milliseconds, microseconds, nanoseconds) and in whether they carry a time zone. Check
dtypesandschemaafter each conversion that matters. - Categoricals and decimals. A pandas
categorybecomes a dictionary-encoded or categorical column elsewhere, and the category order may not survive. Decimals may come back as floats if one side lacks a matching type. - Strings. Polars and Arrow use a native string type, and pandas may use
object. A round trip can change the dtype even when the values are identical.
A small habit prevents most surprises: after a handoff, print the schema and compare row counts and a checksum such as a column sum.
import pandas as pd
import polars as pl
pdf = pd.DataFrame({"id": [1, 2, 3], "score": [1.5, None, 2.5]})
plf = pl.from_pandas(pdf)
assert plf.height == len(pdf)
print(plf.schema)
print("nulls in score:", plf["score"].null_count())With from_pandas, pandas NaN in a float column is converted to a null by default. The null count of 1 confirms that. Without a check like this, you cannot tell whether missing values arrived as nulls or as NaN.
Moving to and from Spark
Spark runs in separate executor processes, usually on other machines. It cannot share memory with your Python session, so every handoff is a transfer.
For small data, convert directly. Enable Arrow so the transfer uses columnar batches instead of pickling rows one by one:
import pandas as pd
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("handoff").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
agg = sdf.groupBy("region").sum("revenue")
result = agg.toPandas() # Spark -> pandas
print(result)createDataFrame(pandas_df) sends the whole pandas frame from the driver to the cluster. toPandas() does the reverse: it collects every row of the result onto the driver, in one process. If the Spark DataFrame is large, this fails with an out-of-memory error or stalls the driver. Aggregate or filter first, then call toPandas() on the small result.
For anything large, go through Parquet instead. Have Spark write the data to shared storage, then read it with Polars or DuckDB:
import duckdb
# Spark side: sdf.write.mode("overwrite").parquet("out/sales")
df = duckdb.sql("SELECT region, sum(revenue) AS revenue FROM 'out/sales/*.parquet' GROUP BY region").df()Spark writes a directory of part files, not a single file, so use a glob such as *.parquet or point the reader at the directory. Polars does the same with pl.scan_parquet("out/sales/*.parquet").
Choosing a handoff
| Situation | Preferred handoff |
|---|---|
| Both tools in one Python process, data fits in memory | Arrow-backed conversion or DuckDB replacement scan |
| Large intermediate result, steps run as separate jobs | Write Parquet, read it in the next step |
| Pandas-only library needs a final small table | Convert at the end with `.to_pandas()` or `.df()` |
| Spark output feeding single-machine analysis | Parquet, then DuckDB or Polars |
| Many tiny handoffs inside a loop | Redesign, so work stays in one engine |
Convert as late as possible and as small as possible. Filter and aggregate in the engine that holds the data, then convert the reduced result. A pipeline that converts a full table back and forth between tools several times loses most of the speed those tools offer.
Exercises
Exercise
A pandas column visits holds integers with some missing values, and you pass the DataFrame to Polars with pl.from_pandas. Why might your integer analysis misbehave, and how would you prevent it?
Show answer
pandas stores an integer column with missing values as float64 with NaN, so the column is no longer an integer type when it reaches Polars. Convert it to a nullable integer type such as Int64 in pandas before the handoff, so the missing values become real nulls. Afterward, check plf.schema and plf["visits"].null_count().
Exercise
Spark produced a 200 GB result, and a teammate wants to run a pandas plot on it. Describe a safe handoff.
Show answer
Do not call toPandas() on the full result, because it collects all rows onto the driver and will run out of memory. Aggregate or sample in Spark down to the size the plot needs, then call toPandas() on that small result. If the full data must be accessible, write it as Parquet and query it with DuckDB or Polars, which can filter and aggregate before anything reaches pandas.